英文:
Golang down casting struct
问题
我相对于Go语言还比较新手,对于初始化结构体有些困惑。
经典的例子是:
type Car struct {
wheelCount int
}
type Ferrari struct {
Car
driver string
}
// 初始化Ferrari
f := Ferrari{Car{4},"Some Dude"}
我的问题是,如果我只有通过构造函数创建的Car,如何得到一个Ferrari呢?
我希望能够像下面这样做:
func NewCar(wheels int) *Car{
return &Car{wheels};
}
car := NewCar(4);
ferrari := Ferrari{car,"Some Dude"}; // 错误:无法将car(类型为*Car)用作字段值中的Car类型
我是否错误地解决了这个问题?是否可以通过某种方式对car进行解引用呢?
英文:
I'm relatively new at Go and struggling with initialising structs.
The classic example is
type Car struct {
wheelCount int
}
type Ferrari struct {
Car
driver string
}
// Initialise Ferrari
f := Ferrari{Car{4},"Some Dude"}
My question is, how do I get a *Ferrari if I only have a *Car created with a constructor?
I would like to be able to to something like the following
func NewCar(wheels int) *Car{
return &Car{wheels};
}
car := NewCar(4);
ferrari := Ferrari{car,"Some Dude"}; // ERROR cannot use car (type *Car) as type Car in field value
Am I approaching the problem incorrectly? Can one simply dereference the car somehow?
答案1
得分: 3
错误消息非常清楚。你不能将Car
用作指向Car
的指针。你需要重新定义你的Ferrari
,将指针嵌入其中:
type Ferrari struct {
*Car
driver string
}
或者在字面量中取消指针的引用:
ferrari := Ferrari{*car, "Some Dude"}
英文:
The error message is pretty clear. You can't use Car
as a pointer to Car
. You need to either redefine your Ferrari
to embed a pointer to Car
type Ferrari struct {
*Car
driver string
}
or to dereference the pointer in the literal:
ferrari := Ferrari{*car, "Some Dude"}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论