为什么不能将嵌入类型作为指针传递[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

有人可以解释为什么这不起作用?如果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
1个回答
0
投票

非常简单。在你的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

*汽车内容确实发生了变化。

© www.soinside.com 2019 - 2024. All rights reserved.