英文:
How is declaring a new struct instance with "var" different from using "new" in Go?
问题
以下代码创建了一个可用的结构体Car
的实例。这与使用new(Car)
有什么不同?
示例:
type Car struct {
make string
}
func Main() {
var car Car; // 这与"car := new(Car)"有什么不同?
car.make = "Honda"
}
英文:
The following code creates a usable instance of the struct, Car
. How is this different than using new(Car)
?
Example:
type Car struct {
make string
}
func Main() {
var car Car; // how is this different than "car := new(Car)"?
car.make = "Honda"
}
答案1
得分: 8
var car Car // 定义变量car是一个Car类型的变量
car2 := new(Car) // 定义变量car2是一个*Car类型的变量,并将一个Car类型的变量赋值给它
car := new(Car)
可以这样实现与 var car Car
的关系:
var x Car
car := &x
英文:
One defines a Car variable, the other returns a pointer to a Car.
var car Car // defines variable car is a Car
car2 := new(Car) // defines variable car2 is a *Car and assigns a Car to back it
car := new(Car)
can be implemented in relation to var car Car
like this:
var x Car
car := &x
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论