Home > Backend Development > Golang > How can I make fields and methods private within a Go struct?

How can I make fields and methods private within a Go struct?

Mary-Kate Olsen
Release: 2024-11-16 19:23:03
Original
292 people have browsed it

How can I make fields and methods private within a Go struct?

Encapsulating Private Fields and Methods in a Go Struct

In Go, the visibility of fields and methods within a struct is controlled by the first character of their names. Fields and methods that start with a capital letter are exported from the package and can be accessed by external code. Conversely, those that start with a lowercase letter are private to the package.

To restrict access to certain fields and methods within a struct, you can place the struct and its member functions in a separate package. This way, only the type defined in the package will have access to the private members.

For instance, in the provided example, you can create a new package for your mytype struct:

// mytype.go

// Define the mytype struct with private fields and methods.
package mytype

type mytype struct {
    size          string
    hash          uint32
}

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

As long as the mytype package does not import any other packages, the fields size and hash and the method doPrivate will remain private to mytype and inaccessible from outside the package.

The above is the detailed content of How can I make fields and methods private within a Go struct?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template