Home  >  Article  >  Backend Development  >  Are Go struct anonymous fields public or private?

Are Go struct anonymous fields public or private?

WBOY
WBOYforward
2024-02-05 23:30:12871browse

Go 结构匿名字段是公共的还是私有的?

Question content

As we all know, fields starting with capital letters are public fields, and fields starting with non-capital letters are private fields. But golang also supports anonymous fields. For example:

type myType struct {
  string
}

These fields are designed for embedding. But is this field public or private?


Correct answer


If the type name of an embedded type is lowercase, it has package visibility. For example:

type t struct {
    string
}

func main() {
    x := t{}
    x.string = "a"
    fmt.println(x)
}

However, if you move the 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
}

The above is the detailed content of Are Go struct anonymous fields public or private?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete