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.
Related
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.
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.
Can someone explain me why this code prints 1 and not 2?
package main
import (
"fmt"
)
type S1 struct{
f1 string
}
type S2 struct{
S1
f2 string
}
func (s *S1) Say(){
fmt.Println("1")
}
func (s *S2) Say(){
fmt.Println("2")
}
type S3 S2
func main() {
var s3 S3
s3.Say()
}
(Runnable at: https://play.golang.org/p/_cjNxBKgSf)
See this answer.
Specifically, from the Go spec we have Method Sets:
Method sets
A type may have a method set associated with it. The method set of an
interface type is its interface. The method set of any other type T
consists of all methods declared with receiver type T. The method set
of the corresponding pointer type *T is the set of all methods
declared with receiver *T or T (that is, it also contains the method
set of T). Further rules apply to structs containing embedded fields,
as described in the section on struct types. Any other type has an
empty method set. In a method set, each method must have a unique
non-blank method name.
Then Struct typess:
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). Within a struct,
non-blank field names must be unique.
Then this:
A field declared with a type but no explicit field name is called an embedded field.
Finally, this:
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.
Promoted fields act like ordinary fields of a struct except that they
cannot be used as field names in composite literals of the struct.
Given a struct type S and a type named 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.
How does all that combine?
You have
type S2 struct{
S1
f2 string
}
which makes S1 an embedded field, and makes S1.Say visible.
Then you have:
type S3 S2
Which makes S3 have the same memory layout and fields as S2, but does not create a type equivalence. This is not saying that S3 "is a" S2, but rather that S3 is not the same as S2, but they do have the same layout.
That layout includes embedded fields, which happens to bring S1.Say into the equation.
Put another way, type S2 has an underlying type of:
struct { S1; f2 string }
and a method called Say.
Type S3 has an identical underlying type of:
struct { S1; f2 string }
But S3 and S2 are not the same, and so S3 does not "inherit" any methods from S2. Instead, S3 inherits only the fields/methods from its underlying type, which are f2, and S1.* (including "Say").
Its important to know, that when you create another name for a type, you can not use the types interchangeably. They are two distinct types for Go's typesystem, even though they share the same underlying representation.
You have two distinct types, S2 and S3. S2 has a function Say, S3 however has not. But since S3 has the same underlying struct as S2, it does have a S1 embedded, which does have a function Say, so thats what gets called.
I'm confused by my experiments with the following program, related to fulfilling interface with struct embedding, with named types and pointer receivers, respectively:
package main
import "fmt"
type MyInt interface {
mytest()
}
type Base struct {
}
func (b *Base) mytest() {
fmt.Println("From base")
}
type Derived struct {
Base
}
type Derived2 struct {
*Base
}
func main() {
// Only this one has problem
// However, if we change mytest's receiver from *Base to Base, all the four assignments are OK
var _ MyInt = Derived{}
// OK
var _ MyInt = &Derived{}
var _ MyInt = Derived2{}
var _ MyInt = &Derived2{}
}
See the comments in the code for my confusions. Are there any principal ways to explain them?
From the Go language specification:
Given a struct type S and a type named T, promoted methods are
included in the method set of the struct as follows:
If S contains an anonymous 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 anonymous
field *T, the method sets of S and *S both include promoted methods
with receiver T or *T.
The case that doesn't work in your code:
var _ MyInt = Derived{}
Here the method set of Derived (which contains an anonymous field Base) includes methods of Base by rule 1. Since mytest is a method of *Base and not Base, it's promoted to a method of *Derived (by the second rule), but not of Derived.
Why is it like that? Well, it's similar to the rule for method sets of structs: methods of T are also methods of T*, but not vice-versa. That's because a method of a pointer receiver can expect to be able to mutate its receiver, but a method of a non-pointer receiver can't.
As per your code function mytest can be called on receiver which pointer to Base.
Struct Derived inherits/embeds Base and Derived2 inherits/embeds *Base i.e. pointer to base.
For
var _MyInt = &Derived2{}: Here pointer of Derived2 is created and since Dervied2 inherits from *Base calling mytest on _MyInt will work
var _MyInt = Derived2{}: Instance of Derived2 is created and since Dervied2 inherits from *Base calling mytest on _MyInt will work
var _MyInt = &Derived{}: Here pointer of Derived is created and since Dervied inherits from Base calling mytest on _MyInt will work
var _MyInt = Derived{}: Instance of Derived is created and since Dervied inherits from Base calling mytest on _MyInt will not work has pointer to Base is expected.
You rightly pointed out that changing receiver from *Base to Base will work because Go will be able recognize Object from pointer and will be able to call mytest.
As per golang specification
A type may have a method set associated with it. The method set of an interface type is its interface. The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T).
Hope this helps
The address of a composite literal is evaluated as the literal itself when used as an interface. Can somebody please point to the part of the ref spec which deals with this ?
package main
import "fmt"
type ntfc interface {
rx() int
}
type cncrt struct {
x int
}
func (c cncrt) rx() int{
return c.x
}
func rtrnsNtfca() ntfc {
return &cncrt{3}
}
func rtrnsNtfc() ntfc {
return cncrt{3}
}
func rtrnsCncrt() *cncrt {
return &cncrt{3}
}
func main() {
fmt.Println(rtrnsNtfca().rx())
fmt.Println(rtrnsNtfc().rx())
fmt.Println(rtrnsCncrt().rx())
}
Also here. For future ref., is it acceptable to just link to the playground without including the code here?
Spec: Method sets:
A type may have a method set associated with it. The method set of an interface type is its interface. The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T).
So the method set of *cncrt includes the methods set of cncrt. Since rx() is an element of cncrt's method set, it will also be in *cncrt's method set. Which means both cncrt and *cncrt types implement the ntfc interface.
If you have a pointer value (*cncrt) and you call rx() on it, the pointer will automatically be dereferenced which will be the receiver of the rx() method.
In your rtnsNtfca() and rtnsNtfc() functions an interface value of ntfc will automatically be created and returned. Interface values in Go are represented as (type;value) pairs (for more details: The Laws of Reflection #The representation of an interface). So both rtnsNtfca() and rtnsNtfc() return an interface value, but the first one holds a dynamic value of type *cncrt and the latter one holds a dynamic value of type cncrt.
And your 3rd method rtrnsCncrt() returns a concrete type (*cncrt), there is no interface wrapping involved there.
Note: "The other way around"
Spec: Calls:
If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m().
This means if you would have declared rx() to have a pointer receiver, and you have a variable of type cncrt (note: not pointer), you could still call the rx() method on it if it is addressable, and the address would be taken automatically and used as the receiver.