本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《如何使用值初始化映射》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~
问题内容我在 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 }
解决方案
错字。您在地图元素后面漏掉了逗号。
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)
}
Playground
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何使用值初始化映射》文章吧,也可关注编程网公众号了解相关技术文章。