Golang中结构体和切片的字段:值混合初始化方法探讨
Golang中结构体和切片的字段:值混合初始化方法探讨 错误:混合使用了字段:值和值初始化器 我不确定我做错了什么,显然我需要更多练习。我基本上是在创建菜单和餐厅结构体,并将它们传递到一个餐厅切片中,以便我可以创建多个菜单和餐厅的实例,但我遇到了混合使用字段:值的错误。有没有更好的方法来做这件事?我是不是完全做错了?我想,既然我向餐厅传递了一个名称和一个继承自菜单的菜单切片,我可以在创建餐厅时这样做,但我正在努力寻找解决这个问题的方法。错误来自餐厅内部的菜单中,我在下面的代码后添加了一张图片,错误在第21行。并排比较是我正在重构的内容。我的代码在左边,我甚至不知道这是否可以做到,右边的代码是我试图重构的。
package main
import "fmt"
type menu struct {
Dish, Hour string
Price float64
}
type restaurant struct {
Name string
Menu []menu
}
type restaurants []restaurant
func main() {
restaurant := restaurants{
restaurant{
Name: "obama's castle",
menu{ <-- 错误在这里
Dish: "potatos",
Hour: "Dinner",
Price: 35.99,
},
},
}
fmt.Println(restaurant)
}

更多关于Golang中结构体和切片的字段:值混合初始化方法探讨的实战教程也可以访问 https://www.itying.com/category-94-b0.html
在你写下“错误在此处”的地方,你定义了一个单一的菜单,但你需要一个数组传入餐厅的菜单字段:
restaurant := restaurants{
restaurant{
Name: "obama's castle",
Menu: []menu{ // 新增部分
menu{
Dish: "potatos",
Hour: "Dinner",
Price: 35.99,
},
}, // 以及闭合括号
},
}
更多关于Golang中结构体和切片的字段:值混合初始化方法探讨的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
你的解决方案很有帮助,确实让我走上了正确的轨道,但我找到了一个替代方案:
package main
import "fmt"
type Menu struct {
Dish, Hour string
Price float64
}
type Restaurant struct {
Name string
Menu
}
// takes type restaurants value of restaurant struct as slice, meaning I can pass multiple
type restaurants []Restaurant
func main() {
r := restaurants{
Restaurant{
Name: "obama's castle",
Menu: Menu{
Dish: "potatos",
Hour: "dinner",
Price: 34.99,
},
},
Restaurant{
Name: "Pizza Palace",
Menu: Menu{
Dish: "Pizza",
Hour: "dinner",
Price: 34.99,
},
},
}
fmt.Println(r)
}
基本上,我只是将我的结构体包装成了一个结构体切片。
在Golang中,结构体和切片的初始化确实有特定的语法规则。你的代码错误是因为在初始化restaurant结构体时,混合使用了字段:值语法和值列表语法。以下是正确的写法:
package main
import "fmt"
type menu struct {
Dish, Hour string
Price float64
}
type restaurant struct {
Name string
Menu []menu
}
type restaurants []restaurant
func main() {
restaurantList := restaurants{
{
Name: "obama's castle",
Menu: []menu{
{
Dish: "potatos",
Hour: "Dinner",
Price: 35.99,
},
},
},
}
fmt.Println(restaurantList)
}
关键修正点:
- 在初始化
restaurant的Menu字段时,需要指定字段名Menu:,因为外层结构体使用了字段:值语法 Menu字段是[]menu切片类型,需要用[]menu{...}语法初始化- 避免变量名与类型名冲突,将变量名改为
restaurantList
如果你想要使用值列表语法(不使用字段名),需要确保所有字段都按顺序提供:
restaurantList := restaurants{
{
"obama's castle",
[]menu{
{"potatos", "Dinner", 35.99},
},
},
}
但混合使用两种语法是不允许的,这就是你遇到错误的原因。

