golang 错误: cannot use XXX literal (type XXX) as type XXX in assignment:XXX does not implement XXX

出错代码如下:

package main

import (
    "fmt"
)

type Speaker interface {
    Hello()
}

type User struct {
    Name string
    Age  int
}

func (this *User) Hello() {
    fmt.Println("hello my name is", this.Name)
}

func main() {

    var s Speaker

    s = User{"wss", 10}

    s.Hello()

}
$ go run main.go
# command-line-arguments
./main.go:24:4: cannot use User literal (type User) as type Speaker in assignment:
	User does not implement Speaker (Hello method has pointer receiver)

解决方法:

func main() {

    var s Speaker

	// 这里将User的指针赋予接口变量
    s = &User{"wss", 10}     

    s.Hello()

}

你可能感兴趣的:(golang)