I just started learning to go on lectures from meil ru and here were a few questions:

1) How to understand the sa := SecretAgent{Person: Person{"James", "12312321321"}, LicenseToKill: true} , namely Person: Person{"James", "12312321321"} what is this for JS? Full code:

 package main import "fmt" type Person struct { Name string inn string } type SecretAgent struct { Person LicenseToKill bool } func (p Person) GetName() string { return p.Name } func main() { sa := SecretAgent{Person: Person{"James", "12312321321"}, LicenseToKill: true} fmt.Println("secret inn", sa.GetName()) } 

2) Why, when you implement interface methods, is it crucial to accept the reference to the parent by value, not pointer? T.e. There is a code:

 package main type Walk interface { Fly() } type Person struct { Name string } func (p Person) Fly() { println("gg") } func main() { p := Person{"gg"} zz(p) } func zz(f Walk) { b := f.(Person) println(b.Name) } 

And it works, but it is worth changing func (p Person) to func (p *Person) and everything breaks down when the structure is passed to the function receiving interface. I understand that this is done because the interface does not know anything about the data and therefore cannot change them by pointer. I'm right?

  • one
    You have 2 unrelated questions here, why don't you break them? - user227465

1 answer 1

  1. SecretAgent{Person: Person{"James", "12312321321"}...

    Person before the colon indicates the name of the field in the SecretAgent structure. Despite the fact that the Person structure is nested in SecretAgent, it can still be accessed as a field. In this case, the name of the field corresponds to the name of the nested structure.

    Person after the colon is the name of the structure being created. In curly brackets are the values ​​of the fields of the created structure in the order of their declaration in the type of structure. In this version of the structure creation - where the field values ​​are specified without their names, all fields must be assigned values.

  2. It is important not to "take the link to the parent by value", but to use the correct types as the interface - i.e. if the method is implemented at the pointer, then the interface corresponds to a pointer to the structure, and not the structure itself.

    For example:

     package main type Walk interface { Fly() } type Person struct { Name string } func (p *Person) Fly() { println("gg") } func main() { p := Person{"gg"} zz(&p) } func zz(f Walk) { b := f.(*Person) println(b.Name) }