How to assign field of struct in a map of Go

huangapple go评论92阅读模式
英文:

How to assign field of struct in a map of Go

问题

我想要给一个包含在映射中的结构体的字段赋值,就像这样:

package main

import (
	"fmt"
)

type Task struct {
    Cmd string
    Desc string
}

var taskMap = map[string]Task{
    "showDir": Task{
        Cmd: "ls",
    },
    "showDisk": Task{
        Cmd: "df",
    },
}

var task = Task{
    Cmd: "ls",
}

func main() {
    // *错误*无法给taskMap["showDir"].Desc赋值
    taskMap["showDir"].Desc = "show dirs"
    task.Desc = "show dirs" // 这是可以的。
    fmt.Printf("%s", taskMap)
    fmt.Printf("%s", task)
}

我可以给变量task中的Desc字段赋值,但不能在封装的映射taskMap中进行赋值,这是怎么回事?

英文:

I want to assign field of struct which is in a map like this:

package main

import (
	"fmt"
)

type Task struct {
    Cmd string
    Desc string
}

var taskMap = map[string] Task{
    "showDir": Task{
        Cmd: "ls",
    },
    "showDisk": Task{
        Cmd: "df",
    },
}

var task = Task{
    Cmd: "ls",
}

func main() {
    // *Error*cannot assign to taskMap["showDir"].Desc
    taskMap["showDir"].Desc = "show dirs" 
    task.Desc = "show dirs" // this is ok.
    fmt.Printf("%s", taskMap)
    fmt.Printf("%s", task)
}

I can assign the Desc field in a variable task but not in a wrapped map taskMap, what has been wrong?

答案1

得分: 1

你可以使用指针:

var taskMap = map[string]*Task{
    "showDir": {
        Cmd: "ls",
    },
    "showDisk": {
        Cmd: "df",
    },
}

func main() {
    taskMap["showDir"].Desc = "显示目录"
    fmt.Printf("%+v", taskMap["showDir"])
}

playground

英文:

You can use pointers:

var taskMap = map[string]*Task{
	"showDir": {
		Cmd: "ls",
	},
	"showDisk": {
		Cmd: "df",
	},
}

func main() {
	taskMap["showDir"].Desc = "show dirs"
	fmt.Printf("%+v", taskMap["showDir"])
}

playground

huangapple
  • 本文由 发表于 2015年1月15日 17:08:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/27959949.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定