Go 如何在结构内部添加切片数组
我希望在Go中创建的结构中添加一个字符串变量数组Go 如何在结构内部添加切片数组,go,Go,我希望在Go中创建的结构中添加一个字符串变量数组 type Recipes struct { //Struct for recipe information name string prepTime int cookTime int recipeIngredient string recipeID int recipeYield int } 它被称为 Recipe1
type Recipes struct { //Struct for recipe information
name string
prepTime int
cookTime int
recipeIngredient string
recipeID int
recipeYield int
}
它被称为
Recipe1.name = "BBQ Pulled Chicken"
Recipe1.prepTime = 25
Recipe1.cookTime = 5
Recipe1.recipeIngredient = "1 8-ounce can reduced-sodium tomato sauce, two"
Recipe1.recipeID = 1
Recipe1.recipeYield = 8
RecipeCredit将包含多个成分,因此它不能是一个字符串。我希望RecipeCredit中有多个数组/切片元素。有谁知道我该如何做到这一点吗?请使用一段
字符串。比如说,
package main
import "fmt"
type Recipe struct {
Name string
PrepTime int
CookTime int
Ingredients []string
ID int
Yield int
}
func main() {
var recipe Recipe
recipe.Name = "BBQ Pulled Chicken"
recipe.PrepTime = 25
recipe.CookTime = 5
recipe.Ingredients = append(recipe.Ingredients,
"1 8-ounce can reduced-sodium tomato sauce",
)
recipe.Ingredients = append(recipe.Ingredients,
"1/2 medium onion, grated ",
)
recipe.ID = 1
recipe.Yield = 8
fmt.Println(recipe)
fmt.Printf("Ingredients: %q\n", recipe.Ingredients)
}
输出:
{BBQ Pulled Chicken 25 5 [1 8-ounce can reduced-sodium tomato sauce 1/2 medium onion, grated ] 1 8}
Ingredients: ["1 8-ounce can reduced-sodium tomato sauce" "1/2 medium onion, grated "]
您需要的是切片,而不是切片数组,也不是数组。:)另一个离题评论/意见:类型为Recipes
的字段中的配方前缀似乎是多余的。而Recipes
应该被称为Recipe
IMHO。看看围棋之旅吧。做所有的练习。