在Golang中为结构体分配切片的映射。

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

Assigning map of slices in a struct in Golang

问题

在Golang中,正确地将切片的映射分配给结构体的方法如下:

package main

import (
	"fmt"
)

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

func main() {
	t := Test{
		name: "myTest",
		testCase: map[string][]string{
			"key": {"value1", "value2"},
		},
	}

	fmt.Println(t)
}

你的代码有一个语法错误,是因为在testCase的映射中,缺少了逗号。我已经帮你修复了这个问题。请使用上述修复后的代码重新尝试。

英文:

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 }

答案1

得分: 1

你在分配值时必须将其类型作为前缀添加。

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

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

不要忘记在项的末尾添加逗号分隔符,因为它使用垂直样式的映射

参考链接

英文:

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

huangapple
  • 本文由 发表于 2022年9月10日 16:28:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/73670367.html
匿名

发表评论

匿名网友

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

确定