为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用值初始化映射

如何使用值初始化映射

Go
智慧大石 2023-07-26 17:12:07
我在 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 }
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

错字。您在地图元素后面漏掉了逗号。


package main


import (

    "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)

}

操场


查看完整回答
反对 回复 2023-07-26
  • 1 回答
  • 0 关注
  • 96 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信