3 ms·
> In particular, there is no shortcut for the zero value for a struct value (not a pointer) — you have to specify the struct name followed by an empty set of br
by pyentropy 5y ago
> In particular, there is no shortcut for the zero value for a struct value (not a pointer) — you have to specify the struct name followed by an empty set of braces
There's no such thing as a struct name. Structs are unnamed. The only way to have a zero valued struct... is, obviously, to instantiate it with its members as zero values. Exactly what struct{members}{} is.
`type X struct { age int }` just makes X refer to a particular type of a struct, but this also works:
var john = struct { age int } { 16 }
- LukeShu 5y agoYou are mistaken. The struct type very literally has a name: type X struct { age int } print(reflect.TypeOf(X{}).Name()) But a name isn't the only thing that may be "magically" bound to a struct. Methods too; if you define methods on `X`, then your `john` won't have those methods. I encourage you to re-read the language spec, paying particular attention to the relationship between "defined types" and "underlying types".
- pyentropy 5y agoThe 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}}