doq13207 2019-07-24 09:03
浏览 12
已采纳

关于接口分配的困惑[重复]

This question already has an answer here:

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

}
</div>
  • 写回答

1条回答 默认 最新

  • douba8048 2019-07-24 10:08
    关注
    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
    ", u.name)
    }
    
    type People struct {
        name string
    }
    
    func (p *People) Work() {
        fmt.Printf("Name : %s
    ", 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()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?