Get operation in a structure in golang [duplicate] - go

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.

Related

How to embed third party types in Go?

In my application, the Decimal package github.com/shopspring/decimal is used.
In order to write custom functions on the decimal.Decimal type, I have created my own Decimal type and embedded decimal.Decimal:
type Decimal struct {
decimal.Decimal
}
This works great, and I can now access decimal.Decimal methods on Decimal object:
a := Decimal{decimal.NewFromFloat(1.0)}
b := Decimal{a.Neg()}
Some of decimal.Decimal methods requires an argument of type decimal.Decimal, f.ex:
c := Decimal{a.Add(b)}
The above line cannot compile because of error: cannot use b (variable of type Decimal) as decimal.Decimal value in argument to a.Add
I have tried to convert Decimal to decimal.Decimal:
c := Decimal{a.Add((decimal.Decimal)(b))}
The above code would not compile due to below error:
cannot convert b (variable of type Decimal) to decimal.Decimal
Question: How to extend/embed a third party type in a way that allows the use of "parent" methods and can use the extended type as argument in methods that requires argument of parents type?
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.
So a quick and dirty solution would be to simply access the field using the "unqualified type name".
_ = Decimal{a.Add(b.Decimal)}
If, however, you're looking for a more seamless experience when using the new type, then your only option is to redeclare the methods that require the original type and use the new type in its place. These redeclared methods need only be simple wrappers that pass the embedded field of one instance to the method of the embedded field of the other instance. For example:
type Time struct {
time.Time
}
func (t Time) In(loc *time.Location) Time {
return Time{t.Time.In(loc)}
}
func (t Time) Equal(u Time) bool {
return t.Time.Equal(u.Time)
}

Weird Behavior of String() Method on Embedded Types in 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.)

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.

Understanding struct embedding

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.

Resources