Home >Backend Development >Golang >How to Encapsulate Private Fields and Methods in Go Structs?

How to Encapsulate Private Fields and Methods in Go Structs?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-06 22:29:10276browse

How to Encapsulate Private Fields and Methods in Go Structs?

Encapsulating Private Fields and Methods for Structs in Go

In Go, achieving true encapsulation for both struct fields and methods is a matter of understanding variable scoping and visibility rules.

By convention, an identifier starting with a capital letter is exported and can be accessed outside the declaring package. Conversely, lowercase identifiers are only accessible within the package itself.

To privatize both the mytype struct and its doPrivate method, the following steps should be taken:

  1. Separate Package: Create a separate package for the mytype struct and its associated methods. This ensures that only the members of the mytype type have access to its private fields and methods.
  2. Lowercase Identifier: Rename both the mytype struct and the doPrivate method to start with lowercase letters.

The resulting code:

// Package mypkg defines the private mytype struct and its methods.
package mypkg

type mytype struct {
    size          string
    hash          uint32
}

// doPrivate can only be accessed by members of mytype.
func (r *mytype) doPrivate() string {
    return r.size
}

Now, only members of the mytype struct can access its private fields and methods. External types or functions within the mypkg package cannot directly access these private members.

The above is the detailed content of How to Encapsulate Private Fields and Methods in Go Structs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn