首页 > 解决方案 > 为什么嵌入式类型不能作为指针传递

问题描述

有人可以解释为什么这不起作用吗?如果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)

}

标签: go

解决方案


很简单。在您的DoMove()函数中,变量是*Vehicle类型(指向Vehicle接口的指针)。指针根本没有方法Move

通常的做法是使用接口作为函数参数,但传入指向结构的指针(并确保指针实现了接口)。例子,

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

*car 内容确实发生了变化。


推荐阅读