-2

I am very confused about the following Go code. Who can tell me why

  1. worker=u and work=&u are valid?
  2. worker=p is valid?
  3. worker=&p is invalid?
  4. What is difference between User and People?
package main

import (
    "fmt"
)

type Worker interface {
    Work()
}

type User struct {
    name string
}

func (u User) Work() {

}

type People struct {
    name string
}

func (p *People) Work() {

}

func main() {
    var worker Worker

    u := User{name:"xxx"}
    worker = u  // valid
    worker = &u  // valid

    p := People{name:"xxx"}
    worker = p  // invalid
    worker = &p  // valid

}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
wangyongjun
  • 145
  • 1
  • 1
  • 9

1 Answers1

2
  1. worker=u and work=&u are valid because User implement all methods of Worker in this case only Work method with values for receivers. Value methods can be invoked on both value and pointer.

  2. worker=p is invalid as People implements Work method with with pointer for receivers. So if you assign any value of People to Worker pointer then if will not Work method. That's why it is invalid.

  3. worker=&p is valid as People implements Work method.

  4. User and People are two different struct that implement same interface Worker. This ensures that both have a method named Work but the implementation may be different.

package main

import (
    "fmt"
)

type Worker interface {
    Work()
}

type User struct {
    name string
}

func (u User) Work() {
    fmt.Printf("Name : %s\n", u.name)
}

type People struct {
    name string
}

func (p *People) Work() {
    fmt.Printf("Name : %s\n", p.name)
}

func main() {
    var worker Worker

    u := User{name: "uuu"}
    worker = u  // valid
    worker = &u // valid
    worker.Work()

    p := People{name: "pppp"}
    // worker = p  // invalid
    worker = &p // valid
    worker.Work()
}