Is Golang struct anonymous field public or private?

Advertisements

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?

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

Leave a ReplyCancel reply