When decoding JSON I've always explicitly written a struct for each object so that I could implement the Stringer interface for individual objects in a parent struct like so:
type Data struct {
Records []Record
}
type Record struct {
ID int
Value string
}
func (r Record) String() string {
return fmt.Sprintf("{ID:%d Value:%s}", r.ID, r.Value)
}
I recently learned that it is possible to do nesting with anonymous structs. This method is much more concise for defining the structure of the data to be decoded:
type Data struct {
Records []struct {
ID int
Value string
}
}
But, is it possible to define a method on a member of a struct, particularly a member which is an anonymous struct? Like the Stringer interface implementation in the first code block.
No, methods can be attached only to named types defined in the same package. From the specs:
A method is a function with a receiver. A method declaration binds an identifier, the method name, to a method. It also associates the method with the receiver's base type.
MethodDecl = "func" Receiver MethodName Signature [ Body ] .
Receiver = "(" [ identifier ] [ "*" ] BaseTypeName ")" .
BaseTypeName = identifier .
The receiver type must be of the form T or *T where T is a type name. The type denoted by T is called the receiver base type; it must not be a pointer or interface type and it must be declared in the same package as the method. The method is said to be bound to the base type and the method name is visible only within selectors for that type.
The type of the Records
field in the second OP example is defined using a type literal, ie. the 'type name' condition above is not met.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With