Home > Blockchain >  Assigning map of slices in a struct in Golang
Assigning map of slices in a struct in Golang

Time:09-10

How to correctly assign a map of slices to a struct in Golang? I tried to following, but it does not work:

package main

import (
    "fmt"
)

type Test struct {
    name     string
    testCase map[string][]string
}

var t = Test{
    name: "myTest",
    testCase: map[string][]string{"key": {"value1", "value2"}}
}

func main() {

    fmt.Println(t)
}

.\main.go:14:61: syntax error: unexpected newline, expecting comma or }

CodePudding user response:

You have to add its type as a prefix when you assign the value.

type Test struct {
    name     string
    testCase map[string][]string
}

var t = Test{
    name: "myTest",
    testCase: map[string][]string{
        "key": {"value1", "value2"},
    },
}

Don't forget to add comma separator at the end of the item, since its use vertical style map

Reference

  • Related