如何使用值初始化映射

我在 Go 中创建了多行地图并设置了值。


type Animal struct {

  food, locomotion, sound string

}


type AnimalInterface interface {

  Eat()

  Move()

  Speak()

}

animals := make(map[string]Animal)

animals["cow"] = Animal{"grass", "walk", "moo"}

animals["bird"] = Animal{"worms", "fly", "peep"}

animals["snake"] = Animal{"mice", "slither", "hsss"}

我更喜欢一步完成创建和初始化。这不起作用...我应该如何解决它?


animals := map[string]Animal{

  "cow": Animal{"grass", "walk", "moo"}

  "bird": Animal{"worms", "fly", "peep"}

  "snake": Animal{"mice", "slither", "hsss"}

}

编辑 添加逗号


  animals := map[string]Animal{

    "cow": Animal{"grass", "walk", "moo"},

    "bird": Animal{"worms", "fly", "peep"},

    "snake": Animal{"mice", "slither", "hsss"}

  }

❯ go run animals.go

# command-line-arguments

./animals.go:109:47: syntax error: unexpected newline, expecting comma or }


智慧大石
浏览 97回答 1
1回答

泛舟湖上清波郎朗

错字。您在地图元素后面漏掉了逗号。package mainimport (    "fmt")type Animal struct {    food, locomotion, sound string}type AnimalInterface interface {    Eat()    Move()    Speak()}func main() {    animals := map[string]Animal{        "cow": Animal{"grass", "walk", "moo"},        "bird": Animal{"worms", "fly", "peep"},        "snake": Animal{"mice", "slither", "hsss"},    }    fmt.Println(animals)}操场
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go