1

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
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
river
  • 694
  • 6
  • 22

3 Answers3

4

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.

Willis Blackburn
  • 8,068
  • 19
  • 36
  • 1
    You can use a pointer to an interface variable to change the value of the variable from another scope. If you have `func f(a Animal)` then you can use `a` in the function to invoke `Animal` methods, but if you change the value of `a` itself, that change is only visible within `f`. If you instead write `func f(a *Animal)` then `a` is now a pointer to some interface variable defined elsewhere, and you can change that variable by setting `*a`. – Willis Blackburn Feb 02 '19 at 16:15
1

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()
}

AmirSo
  • 49
  • 1
  • 7
-1

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.

HolaYang
  • 419
  • 2
  • 10
  • If I use `Dog` to implement `Animal`, `var a *Animal=new(Dog) ` fails too! Why? @HolaYang – river Feb 02 '19 at 06:03
  • That's another problem, a pointer to interface is almost never useful in golang.w – HolaYang Feb 02 '19 at 12:34
  • Read [this](https://stackoverflow.com/questions/44370277/type-is-pointer-to-interface-not-interface-confusion) for more information. – HolaYang Feb 02 '19 at 12:36