简体   繁体   中英

Can't assign a struct pointer to a interface pointer

The struct Dog implemetments all the methods of interface Animal , why does *Dos can't be assigned to *Animal ?

type Animal interface {
    run()
}

type Dog struct {
    name string
}

func (d *Dog) run() {
    fmt.Println( d.name , " is running")
}

func main(){
    var d *Dog
    var a *Animal

    d = new(Dog)
    d.run()
    a = d   //errors here
}

Go informs the following errros:

Cannot use 'd' (type *Dog) as type *Animal in assignment

A variable with an interface type is already a pointer; you don't need to declare it as a pointer to an interface. Just do var a Animal and it will work.

You must remove pointer from interface.


//Animal interface
type Animal interface {
    run()
}

//Dog struct
type Dog struct {
    name string
}

func (d *Dog) run() {
    fmt.Println(d.name, "is running")
}

func main() {
    var d *Dog
    var a Animal

    d = new(Dog)
    d.name = "Putty"
    d.run()
    a = d //errors here
    a.run()
}

Dog is a type, so *Dog is.

Dog DOES NOT implement the interface Animal , but *Dog does.

So var a Animal = new(Dog) is ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM