在匿名结构体内初始化字段。

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

Initializing a field inside an anonymous struct

问题

给定这个匿名结构体:

var myMap struct {
  list       map[string]string
  someStuff *some.Object
}

我可以在一个声明中初始化listsomeStuff吗?

这样是不起作用的:

var myMap struct {
  list       map[string]string = make(map[string]string)
  someStuff *some.Object = &some.Object{}
}
英文:

Given this anonymous struct:

var myMap struct {
  list       map[string]string
  someStuff *some.Object
}

Can I initialize the list and someStuff in one declaration?

This doesn't work:

var myMap struct {
  list       map[string]string = make(map[string]string)
  someStuff *some.Object = &some.Object{}
}

答案1

得分: 12

这是翻译好的内容:

这是你要的代码示例

var myMap = struct {
  list map[string]string
  str string
}{
  list: map[string]string{"hello":"string"},
  str: "myString",
}

你也可以这样写

var myMap = struct {
  list map[string]string
  str string
}{map[string]string{"hello":"string"}, "myString"}

这是一个可运行的示例[Go PlayGround](https://play.golang.org/p/j1l2epoB_s)。

所以你声明了一个结构体然后在花括号中初始化它。(我是从这个[旧的 Go talk](https://talks.golang.org/2012/10things.slide#3)中学到的。)
英文:

Here you go:

var myMap = struct {
  list map[string]string
  str string
}{
  list: map[string]string{"hello":"string"},
  str: "myString",
}

You can also do it this way:

var myMap = struct {
  list map[string]string
  str string
}{map[string]string{"hello":"string"}, "myString"}

And a working example: <kbd>Go PlayGround</kbd>.

So you declare your structure and then in curly braces you initiate it. (I learned it from this old go talk.)

答案2

得分: 7

是的,你可以这样做。看看这个例子:

package main

import "fmt"

func main() {
    myMap := struct {
        list       map[string]string
        someStuff interface{}
    }{
        list: make(map[string]string),
        someStuff: 2,
    }

    fmt.Println(myMap)
}
英文:

Yes, you can do this. Look at this example:

package main

import &quot;fmt&quot;

func main() {
    myMap := struct {
        list       map[string]string
        someStuff interface{}
    }{
        list: make(map[string]string),
        someStuff: 2,
    }

    fmt.Println(myMap)
}

huangapple
  • 本文由 发表于 2015年11月25日 04:18:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/33903020.html
匿名

发表评论

匿名网友

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

确定