这个问题在这里已有答案:
有人可以解释为什么这不起作用?如果DoMove
采用结构而不是指针,它可以工作。
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)
}
非常简单。在你的DoMove()
函数中,变量是*Vehicle
类型(指向Vehicle
接口的指针)。指针根本没有方法Move
。
通常的做法是使用接口作为函数参数,但将指针传递给struct(并确保指针实现接口)。例,
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())
}
输出:
Moving...
Moved
*汽车内容确实发生了变化。