我在 Go 的 youtube 教程中看到的关于以下代码的两个问题。尝试阅读这段代码,我看到指针结构的片段被分配给 productList... 好的,这很好,但为什么要使用 & 符号来表示 Product?(我知道这是地址)。我知道当你想传递给函数时,struct 确实会用 & 标记(因为它默认按值传递)但即使我知道如果接收器是指针,你也不需要使用 & .. 那么为什么在这里使用 & ? type Product struct { ID int name string}var productList = []*Product{ &Product{ ID: 1, Name: "Latte", }, &Product{ ID: 2, Name: "Ice Coffee", },}换句话说,上面和下面有什么区别?var productList = []*Product{ Product{ ID: 1, Name: "Latte", }, Product{ ID: 2, Name: "Ice Coffee", },}
1 回答

交互式爱情
TA贡献1712条经验 获得超3个赞
var productList = []*Product
表示这productList是一个指针列表。每个指针指向一个Product.
如果你这样做
var productList = []*Product{
Product{
ID: 1,
Name: "Latte",
}
}
您正在productList使用类型的事物Product列表而不是类型指针的列表进行初始化Product(这是非法的,并且会引发编译时错误,说“不能使用产品文字(类型产品)作为切片文字中的*产品类型)。
- 1 回答
- 0 关注
- 85 浏览
添加回答
举报
0/150
提交
取消