Weird Behavior of String() Method on Embedded Types in Go - go

I'm not able to understand how the String() method works for embedded structs in Go. Consider this:
type Engineer struct {
Person
TaxPayer
Specialization string
}
type Person struct {
Name string
Age int
}
func (p Person) String() string {
return fmt.Sprintf("name: %s, age: %d", p.Name, p.Age)
}
type TaxPayer struct {
TaxBracket int
}
func (t TaxPayer) String() string {
return fmt.Sprintf("%d", t.TaxBracket)
}
func main() {
engineer := Engineer{
Person: Person{
Name: "John Doe",
Age: 35,
},
TaxPayer: TaxPayer{3},
Specialization: "Construction",
}
fmt.Println(engineer)
}
The output of this code is {name: John Doe, age: 35 3 Construction}. But if I remove the Person.String() method definition then the output is just 3 (it calls engineer.TaxPayer.String()). However if I remove TaxPayer.String() method definition as well, then the output is {{John Doe 35} {3} Construction}. I initially thought there must be an implicit String() method defined for the overall Engineer struct, but there is no such method.
Why is method invocation behaving this way? If I instead have the methods for each embedded type named anything other than String() (say Foo()), and then try to do fmt.Println(engineer.Foo()), I get an (expected) compilation error: ambiguous selector engineer.Foo. Why is this error not raised when the methods' name is String() instead?

If you embed types in a struct, the fields and methods of the embedded type get promoted to the embedder type. They "act" as if they were defined on the embedder type.
What does this mean? If type A embeds type B, and type B has a method String(), you can call String() on type A (the receiver will still be B, this is not inheritance nor virtual method).
So far so good. But what if type A embeds type B and type C, both having a String() method? Then A.String() would be ambiguous, therefore in this case the String() method won't be promoted.
This explains what you experience. Printing Engineer will have the default formatting (struct fields) because there would be 2 String() methods, so none is used for Engineer itself. Of course the default formatting involves printing the fields, and to produce the default string representation of a value, the fmt package checks if the value being printed implements fmt.Stringer, and if so, its String() method is called.
If you remove Person.String(), then there is only a single String() method promoted, from TaxPlayer, so that is called by the fmt package to produce the string representation of the Engineer value itself.
Same goes if you remove TaxPayer.String() : then Person.String() will be the only String() method promoted, so that is used for an Engineer value itself.
This is detailed in Spec: Struct types:
A field or method f of an embedded field in a struct x is called promoted if x.f is a legal selector that denotes that field or method f.
[...] Given a struct type S and a defined type T, promoted methods are included in the method set of the struct as follows:
If S contains an embedded field T, the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T.
If S contains an embedded field *T, the method sets of S and *S both include promoted methods with receiver T or *T.
The first sentence states "if x.f is a legal selector". What does legal mean?
Spec: Selectors:
For a primary expression x that is not a package name, the selector expression
x.f
denotes the field or method f of the value x.
[...] A selector f may denote a field or method f of a type T, or it may refer to a field or method f of a nested embedded field of T. The number of embedded fields traversed to reach f is called its depth in T. The depth of a field or method f declared in T is zero. The depth of a field or method f declared in an embedded field A in T is the depth of f in A plus one.
The following rules apply to selectors:
For a value x of type T or *T where T is not a pointer or interface type, x.f denotes the field or method at the shallowest depth in T where there is such an f. If there is not exactly one f with shallowest depth, the selector expression is illegal.
[...]
The essence is emphasized, and it explains why none of the String() methods are called in the first place: Engineer.String() could come from 2 "sources": Person.String and TaxPayer.String, therefore Engineer.String is an illegal selector and thus none of the String() methods will be part of the method set of Engineer.
Using an illegal selector raises a compile time error (such as "ambiguous selector engineer.Foo"). So you get the error because you explicitly tried to refer to engineer.Foo. But just embedding 2 types both having String(), it's not a compile-time error. The embedding itself is not an error. The use of an illegal selector would be the error. If you'd write engineer.String(), that would again raise a compile time error. But if you just pass engineer for printing: fmt.Println(engineer), there is no illegal selector here, you don't refer to engineer.String(). It's allowed. (Of course since method set of Engineer does not have a promoted String() method, it won't be called to produce string representation for an Engineer–only when printing the fields.)

Related

what is the different between (&t).value and t.value in golang? t is a struct

I have such a struct in golang like below:
type test struct {
value int
}
and when I tried this
t := test{1}
fmt.Println((&t).value)
fmt.Println(t.value)
the compiler did not report an error,and I got the same output of 1,
this output confused me.What is different between (&t).value and t.value in golang?
The selector expression p.f where p is a pointer to some struct type and f is a field of that struct type is shorthand for (*p).f.
Your expression (&t) results in a value of the pointer type *test. So that makes (&t).value the shorthand for (*(&t)).value.
Selectors:
The following rules apply to selectors:
For a value x of type T or *T where T is not a pointer
or interface type, x.f denotes the field or method at the
shallowest depth in T where there is such an f. If there is not
exactly one f with shallowest depth, the selector expression is
illegal.
For a value x of type I where I is an interface type,
x.f denotes the actual method with name f of the dynamic value
of x. If there is no method with name f in the method set of
I, the selector expression is illegal.
As an exception, if the type of x is a defined pointer type
and (*x).f is a valid selector expression denoting a field (but
not a method), x.f is shorthand for (*x).f.
In all other cases, x.f is illegal.
If x is of pointer type and has the value nil and x.f
denotes a struct field, assigning to or evaluating x.f causes a
run-time panic.
If x is of interface type and has the value nil, calling or
evaluating the method x.f causes a run-time panic.

Get operation in a structure in golang [duplicate]

This question already has answers here:
Embedding instead of inheritance in Go
(7 answers)
Closed last year.
Below is a simple program. But what I don't understand is that how is the Get operation working? I have not defined any Get Method, but form.Get is working. How?
Sincerely,
Sudarsan.D
package main
import (
"fmt"
"net/url"
)
type errors map[string]string;
type Form struct {
url.Values;
Errors errors;
}
func New (data url.Values) (*Form) {
return &Form {
data,
errors(map[string]string{}),
};
}
func main () {
k1 := url.Values{};
k1.Set("arvind","superstar");
k1.Set("title","Arvind");
form := New(k1);
fmt.Println("The title is", form.Get("arvind"));
}
Because in the Form struct you did not provide a name explicitly for the url.Values field, that field is said to be embedded. An embedded field's name is automatically set to the type's unqualified name, i.e. in this case the url.Values field's name becomes Values. Also, an embedded field type's methods (if it has any) and fields (if it is a struct with any) are said to be promoted to the embedding struct. A promoted method or field can be accessed directly through the embedding struct, without having to specify the embedded field's name. i.e. instead of form.Values.Get("arvind") you can do form.Get("arving").
Keep in mind that the two expressions form.Values.Get("arvind") and form.Get("arving") are semantically equivalent. In both cases you are calling the method Get on the form.Values field even though in the second expression the field's name is omitted.
From the language spec on Struct types:
A struct is a sequence of named elements, called fields, each of which
has a name and a type. Field names may be specified explicitly
(IdentifierList) or implicitly (EmbeddedField).
...
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.
...
A field or method f of an embedded field in a struct x is called
promoted if x.f is a legal selector that denotes that field or method
f.
...
Given a struct type S and a defined type T, promoted methods are
included in the method set of the struct as follows:
If S contains an embedded field T, the method sets of S and *S both
include promoted methods with receiver T. The method set of *S also
includes promoted methods with receiver *T.
If S contains an embedded
field *T, the method sets of S and *S both include promoted methods
with receiver T or *T.

Anonymous/explicitly embedded a interface in struct

type A interface {
f()
}
type B struct {
A
}
type C struct {
Imp A
}
func main() {
b := B{}
c := C{}
//b can be directly assigned to the A interface, but c prompts that it cannot be assigned
var ab A = b
//Cannot use 'c' (type C) as type A in assignment Type does not implement 'A' as some methods are missing: f()
var ac A = c
}
what's the different between in the B struct and C struct?
in Go sheet
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.
If you continue reading the same section of the spec of the spec, you will notice the following:
Given a struct type S and a defined type T, promoted methods are
included in the method set of the struct as follows:
If S contains an embedded field T, the method sets of S and *S both
include promoted methods with receiver T. The method set of *S also
includes promoted methods with receiver *T.
If S contains an embedded
field *T, the method sets of S and *S both include promoted methods
with receiver T or *T.
Your struct B has no methods explicitly defined on it, but B's method set implicitly includes the promoted methods from the embedded field. In this case, the embedded field is an interface with method f(). You can use any object that satisfies that interface and its f() method will automatically be part of the method set for B.
On the other hand, your C struct has a named field. The methods on Imp do not get automatically added to C's method set. Instead, to access the f() method from Imp, you would need to specifically call C.Imp.f().
Finally: the fact that you're using an interface as the (embedded or not) field does not matter, it could easily be another struct that has a f() method. The important part is whether f() becomes part of the parent struct's method set or not, which will allow it to implement A or not.

Do embedded fields count towards interfaces

In Golang, I can have an embedded fields inside of a struct. The embedded field gets "promoted", and the new struct gets to use all the functions of the embedded fields as if it's part of itself. So my question is, does the embedded fields' functions count towards interface implementation? For example:
type Foo struct {
Name string
}
func (f *Foo) Name() {
fmt.Println(f.Name)
}
type Hello interface {
Name()
Hello()
}
type Bar struct {
World string
*Foo
}
func (b *Bar) Hello() {
fmt.Println("Hello")
}
In the code above, Bar{} does not implement a function named Name(), but Foo{} does. Since Foo{} is an embedded field inside of Bar{}, is Bar{} a Hello type?
Here's how to trace this down in the language specification
Find out what it means to implement an interface in the "Interface types" section:
Interface types ¶
An interface type specifies a method set called its interface. A
variable of interface type can store a value of any type with a method
set that is any superset of the interface. Such a type is said to
implement the interface.
Or from the section on "Method sets"
The method set of a type determines the interfaces that the type implements...
So what is important is the method set of the type you want to implement the interface. Let's see what constitutes a method set in the case of embedded fields:
The first place I checked was the section "Method Sets", but it sends us elsewhere:
Further rules apply to structs containing embedded fields, as described in the section on struct types.
So we go to the section "Struct types" and find:
A field or method f of an embedded field in a struct x is called
promoted if x.f is a legal selector that denotes that field or method
f.
...
Given a struct type S and a defined type T, promoted methods are
included in the method set of the struct as follows:
If S contains an embedded field T, the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T.
If S contains an embedded field *T, the method sets of S and *S both include promoted methods with receiver T or *T.
So, given that the methods of the embedded field are promoted, they are included in the method set of the containing struct. As we saw above the method set of any type is what determines whether it implements an interface.

Why can I assign struct functions to members of other structs?

I was just messing around and wrote the below piece of code,
package main
import (
"fmt"
)
type Person struct {
name string
}
func (p Person) printName() {
fmt.Println(p.name)
}
type Man struct {
name string
f func()
}
func main() {
p := Person{name: "John"}
m := Man{name: "Adam"}
m.f = p.printName
p.printName()
m.f()
}
The above code results in the following output. This works across packages too.
John
John
So, here are my questions.
Why does this work?
Struct methods require receivers of the same type. How is the function still able to access members of the Person struct?
What happens when m.f = p.printName is executed in the above example?
This question deals mostly with receivers and may extend a bit to embedding.
From the relevant section of the spec:
A method is a function with a receiver. A method declaration binds an
identifier, the method name, to a method, and associates the method
with the receiver's base type.
MethodDecl = "func" Receiver MethodName Signature [ FunctionBody ] .
Receiver = Parameters .
The receiver is specified via an extra parameter section preceding the
method name. That parameter section must declare a single non-variadic
parameter, the receiver. Its type must be of the form T or *T
(possibly using parentheses) 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 defined 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 type T or *T.
A non-blank receiver identifier must be unique in the method
signature. If the receiver's value is not referenced inside the body
of the method, its identifier may be omitted in the declaration. The
same applies in general to parameters of functions and methods.
For a base type, the non-blank names of methods bound to it must be
unique. If the base type is a struct type, the non-blank method and
field names must be distinct.
Given type Point, the declarations
func (p *Point) Length() float64 {
return math.Sqrt(p.x * p.x + p.y *p.y)
}
func (p *Point) Scale(factor float64) {
p.x *= factor
p.y *= factor
}
bind the methods Length and Scale, with receiver type *Point, to the
base type Point.
The type of a method is the type of a function with the receiver as
first argument.
For instance, the method Scale has type
func(p *Point, factor float64)
However, a function declared this way is not a method.
Man has a field named f that is a function that takes no arguments and returns nothing.
As we saw above golang internally treats
func (p Person) printName()
as
func printName(p Person)
and this can be considered as a function of no arguments when it acts on a Person struct (and it does because p is a Person and p.printName acts on p). Therefore it is allowed to be assigned to Man.f
So the moment you assigned the f field on the Man struct to a function that has captured the Person instance with name "John" and reads the name from that, therefore you get effect of the second "John" being printed.
The Man.name field has never come into play on that one.
I suspect that what you would expect as normal behaviour can be achieved with struct embedding of Person into a Man.
here is a playground link to demonstrate that
A method, in Go, is basically a function with a receiver. That receiver is wraped by the compiler, and beyond that, there is nothing more different from a normal function. That means, at anywhere, the method always gets the receiver which it is bound to, no matter how you call it, assign it to another variable or anythiing else.
In your code, f is not a method of type Man. It is merely a field of type func(). You can set to anything that match the signature, and the function will know nothing about Man or its instance. That means, m.f has no knowledge of m and no access to m.name or any other field of m.
And a note, you can call methods like: Person.PrintName(p) where p is of type Person.
function in Golang is also a value, it can be passed as parameter or assigned by other function too, method in Golang is also a function, with one different, it has receiver in it's value, so when use assign a method to a function (which have same signature) it's refer to the receiver and executing code in that method to destination function

Resources