3 ms·
The spec very clearly settles the issue: 1. A struct is a sequence of named elements, called fields, each of which has a name and a type. // An empty stru
by pyentropy 5y ago
The spec very clearly settles the issue:
1. A struct is a sequence of named elements, called fields, each of which has a name and a type.
// An empty struct.
struct {}
// A struct with 6 fields.
struct {
x, y int
u float32
_ float32 // padding
A *[]int
F func()
}
2. A type declaration binds an identifier, the type name, to a type.
The new type is called a defined type. It is different from any other type, including the type it is created from.
type TreeNode struct {
left, right *TreeNode
value *Comparable
}
--
type X struct {} is simply a type named X, of underlying type struct{} which (I'm refering to the struct here) cannot have a name - because it is an ordered sequence [(name, type), (name2, type2), ...], not a product type (X, [...]).
I don't know why you bring methods to this, as if methods are somehow connected to structs. In your reflection example: Name() returns:
(1) the name of a defined type
(2) the empty string for all other cases
It is designed for all types, and is of no particular meaning to the struct type, more than it is to int64 or float64. Would you say "ints have names"? You can create a type with a name and/or methods having such underlying types too.
I don't wanna nitpick in any case - my point was structs are not an exception like OP mentions. The brace syntax is a composite literal, and maps, arrays, slices all use it. The latter just don't use it for creating zero valued objects, because they are dynamic and are nil valued.
Both declaring a value without a specific value (var john struct{} or var john X) or a literal (struct{}{} and X{}), seem concise to me. Unless we bring inference to the table:
map[string]struct{age int}{"A": {15}, "B": {18}}