1

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?

armnotstrong
  • 8,605
  • 16
  • 65
  • 130
  • thank you, I found a way to make this work according to the question you referred, which is copy the `Task` of the `taskMap`, change it and put it back in to the map again, but I just found it's weird as not to change it just in place. – armnotstrong Jan 15 '15 at 16:58

1 Answers1

1

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

OneOfOne
  • 95,033
  • 20
  • 184
  • 185