This question already has an answer here:
Can someone explain why this doesn't work? It works if DoMove
takes a struct instead of a pointer.
package main
import (
"fmt"
)
type Vehicle interface {
Move()
}
type Car interface {
Vehicle
Wheels() int
}
type car struct {}
func (f car) Move() { fmt.Println("Moving...") }
func (f car) Colour() int { return 4 }
func DoMove(v *Vehicle) {
v.Move()
}
func main() {
f := car{}
DoMove(&f)
}
</div>
Very simple. In your DoMove()
function, the variable is of *Vehicle
type (pointer to the Vehicle
interface). The pointer has no method Move
at all.
The usual practice is to use the interface as function argument, but pass in pointer to struct (and make sure the pointer implements the interface). Example,
package main
import (
"fmt"
)
type Vehicle interface {
Move()
}
type Car interface {
Vehicle
Wheels() int
}
type car struct {
status string
}
func (f *car) Move() {
fmt.Println("Moving...")
f.status = "Moved"
}
func (f car) Status() string {
return f.status
}
func DoMove(v Vehicle) {
v.Move()
}
func main() {
f := car{status: "Still"}
DoMove(&f)
fmt.Println(f.Status())
}
Output:
Moving...
Moved
The *car content is indeed changed.