Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private fields and methods for a struct

Tags:

go

In the following test code I would like to have both mytype and the doPrivate method private, so that only members of mytype can access it, but not other types\functions in the scope of the mypackage package.

Can I do this in golang?

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") } 

Fields size and hash as well as the doPrivate method should be encapsulated and no other type should have access to them.

like image 540
andrew.fox Avatar asked Mar 03 '14 13:03

andrew.fox


People also ask

Can struct have private members C#?

This struct can access private members from a struct of the same type. As others have pointed out, this behavior is the same for class types as well.

What are private fields?

Private fields are accessible on the class constructor from inside the class declaration itself. They are used for declaration of field names as well as for accessing a field's value. It is a syntax error to refer to # names from out of scope.

Should structs be public or private?

Though classes defined using either keyword can have public , private and protected base classes and members, the default choice for classes defined using class is private , whilst for those defined using struct the default is public .

What are private methods in JavaScript?

Private methods are defined in JavaScript to hide crucial class methods or keep sensitive information private. In a class, to define a private method instance, private static method, or a private getter and setter, you have to prefix its name with the hash character #.


1 Answers

In Go, an identifier that starts with a capital letter is exported from the package, and can be accessed by anyone outside the package that declares it.

If an identifier starts with a lower case letter, it can only be accessed from within the package.

If you need members in a type to only be accessed by members of that type, you then need to place that type and its member functions in a separate package, as the only type in that package.

like image 172
nos Avatar answered Sep 22 '22 06:09

nos