Home > Backend Development > Golang > Can you make struct fields and methods private in Go packages?

Can you make struct fields and methods private in Go packages?

DDD
Release: 2024-11-15 10:10:02
Original
679 people have browsed it

Can you make struct fields and methods private in Go packages?

Unable to Create Private Fields and Methods for Structs in a Package

Question:

Is it possible to set a struct's field and method as private within a Go package, accessible only by members of that struct, but not by other package functions or external code?

Context:

Consider the following code snippet:

package mypackage

type mytype struct {
    size          string
    hash          uint32
}

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

func (r *mytype) Do() string {
    return doPrivate("dsdsd")
}
Copy after login

In this case, the size and hash fields and the doPrivate method should be encapsulated within mytype, inaccessible to other types.

Answer:

While Go allows you to export or hide an identifier based on its capitalization, the concept of private class members or data hiding does not exist in Go.

By convention, exported identifiers (initialized with a capital letter) are intended for public use within a package. Conversely, unexported identifiers (initialized with a lowercase letter) have restricted access within that package.

However, within a given package, there is no way to further restrict access to struct members beyond that package scope. To achieve data encapsulation, the suggested approach is to create a separate package where the entire struct and its associated methods are the only elements defined within that package.

The above is the detailed content of Can you make struct fields and methods private in Go packages?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template