Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Go struct anonymous field public or private? [duplicate]

Tags:

struct

go

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?

like image 914
SOS Avatar asked Oct 31 '25 00:10

SOS


1 Answers

From the specification on struct types:

A field declared with a type but no explicit field name is called an embedded field. An embedded field must be specified as a type name T or as a pointer to a non-interface type name *T, and T itself may not be a pointer type. The unqualified type name acts as the field name.

The unqualified name of string is string.

From the specification on exported identifiers:

An identifier may be exported to permit access to it from another package. An identifier is exported if both:

  1. the first character of the identifier's name is a Unicode uppercase letter (Unicode character category Lu); and
  2. the identifier is declared in the package block or it is a field name or method name.

The first character of string is not a Unicode uppercase letter.

It follows that the embedded field is not exported. In other words, it's private to the package.

like image 102
Bryan Newbold Avatar answered Nov 01 '25 13:11

Bryan Newbold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!