程序开发 · 2024年8月17日

Go – 如何更新作为结构体字段的映射?

当前位置: > > > > Go – 如何更新作为结构体字段的映射?

来源:stackoverflow
2024-04-19 12:39:34
0浏览
收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《Go – 如何更新作为结构体字段的映射?》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我尝试了以下方法来更新声明为结构字段的空映射:

package main

type MyStruct struct {
    scoreboard map[string]int
}

func main() {
    mystruct := NewMyStruct()
    mystruct.SubmitWord('test')
}

func NewMyStruct() MyStruct {
    return MyStruct{}
}

func (mystruct *MyStruct) SubmitWord(word string) int {
    mystruct.scoreboard[word] = len(word)
    return len(word)
}

但我收到 exit 状态 2 的错误。

有问题的行是 mystruct.scoreboard[word] = len(word)

我能找到的任何内容似乎都表明这是可以的,但我还没有找到地图位于结构内的任何其他示例。

解决方案

您需要先分配地图

package main


type MyStruct struct {
    scoreboard map[string]int
}

func main() {
    mystruct := NewMyStruct()
    mystruct.SubmitWord("test")
}

func NewMyStruct() MyStruct {
    var x MyStruct
    x.scoreboard=make(map[string]int)
    return x
}

func (mystruct *MyStruct) SubmitWord(word string) int {
    mystruct.scoreboard[word] = len(word)
    return len(word)
}

演示:

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Go – 如何更新作为结构体字段的映射?》文章吧,也可关注公众号了解相关技术文章。