go - 为什么嵌入式类型不能作为指针传递
问题描述
有人可以解释为什么这不起作用吗?如果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
。
通常的做法是使用接口作为函数参数,但传入指向结构的指针(并确保指针实现了接口)。例子,
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 内容确实发生了变化。
推荐阅读
- c++ - 在将变量作为输入之前使用变量定义其他变量
- javascript - 未捕获的类型错误:$(...).uploadify 不是函数
- keycloak - 一旦用户在 keycloak 中被禁用,有没有办法从组织站点注销用户?
- python - 当表单未填写python tkinter时,我想添加错误页面
- printing - 如何通过 vpn 连接网络打印机
- php - Laravel finally 回调并不总是在批处理作业上调用
- mariadb - 这些 MariaDB 死锁背后的原因
- python - Airflow PythonVirtualOperator 不安装 pip 包
- java - Duration.toHours 返回零
- go - 在 golang switch 语句中更改变量值