Are Go struct anonymous fields public or private?

WBOY
Release: 2024-02-05 23:30:12
forward
870 people have browsed it

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
}
Copy after login

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)
}
Copy after login

However, if you move the type t to another package p:

package p

type t struct {
  string
}
Copy after login
package main

import "testmod/p"

func main() {
    x := p.T{}
    x.string = "a" // Error
}
Copy after login

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!

source:stackoverflow.com
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!