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

How to Encapsulate Private Fields and Methods in Go Structures?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-08 06:26:10815browse

How to Encapsulate Private Fields and Methods in Go Structures?

Private Fields and Methods for a Structure

In Go, when working with structures, sometimes there's a need to have certain fields and methods as private, meaning that only the members of that structure can access them, while other types or functions within the scope of the package should not have access.

To achieve this, it's important to note that in Go, identifiers starting with capital letters are exported from the package and can be accessed by entities outside the declaring package. Conversely, identifiers starting with lowercase letters are only accessible within the package itself.

If the goal is to have members of a type be accessible only by members of that type, it's necessary to place that type, along with its member functions, in a separate package, as the sole type in that package. By doing so, the type and its members will be private to that package and cannot be accessed from outside.

Here's how to modify the code to make the mytype struct and doPrivate method private:

// Define a separate package for mytype.
package mytypepkg

type mytype struct {
    size string
    hash uint32
}

func (r *mytype) doPrivate() string {
    return r.size
}

Now, mytype and doPrivate are encapsulated within their own package, making them inaccessible from other types or functions outside of that package.

The above is the detailed content of How to Encapsulate Private Fields and Methods in Go Structures?. 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