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?

1
  • 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. Commented Jan 15, 2015 at 16:58

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.