Golang向下转换结构体

huangapple go评论85阅读模式
英文:

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"}

huangapple
  • 本文由 发表于 2015年6月19日 17:37:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/30934792.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定