0

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"));
}
Sudarsan
  • 303
  • 2
  • 5

1 Answers1

1

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.
mkopriva
  • 35,176
  • 4
  • 57
  • 71