Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is Golang struct anonymous field public or private?

As we know, fields start with capital letters are public, and those are not are private. But Golang also support anonymous field. For example:

type myType struct {
  string
}

These fields are design for Embedding. But is this field public or private?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If the typename of the embedded type is lower case, it has package visibility. For example:

type T struct {
    string
}

func main() {
    x := T{}
    x.string = "a"
    fmt.Println(x)
}

However if you move type T to another package p:

package p

type T struct {
  string
}

package main

import "testmod/p"

func main() {
    x := p.T{}
    x.string = "a" // Error
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading