如何使用指向字符串的指针切片初始化一个变量?

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

How to initialize a variable with slice of pointers to string?

问题

以下是代码的翻译:

package main

type T struct {
    m1 *string
    m2 *string
    m3 *string
    m4 *string
}

type SliceT = []*T

func main() {

    sliceT := SliceT{
        {
            m1: "0000000001", // & 操作符适用于变量,但不适用于无类型字符串常量
            m2: "00000002",
            m3: "abc",
            m4: "def",
        },
        {
            m1: "0001",
            m2: "0000012",
            m3: "aaa",
            m4: "bbb",
        },
        {
            m1: "00003",
            m2: "002",
            m3: "ccc",
            m4: "fff",
        },
    }

}

如何初始化 sliceT?复合字面量在这里无法帮助...

英文:

Below is the code:

package main

type T struct {
	m1 *string
	m2 *string
	m3 *string
	m4 *string
}

type SliceT  = []*T

func main() {

	sliceT := SliceT{
		{
			m1: "0000000001", // & operator works on variable but not on untyped string constant
			m2: "00000002",
			m3: "abc",
			m4: "def",
		},
		{
			m1: "0001",
			m2: "0000012",
			m3: "aaa",
			m4: "bbb",
		},
		{
			m1: "00003",
			m2: "002",
			m3: "ccc",
			m4: "fff",
		},
	}

}

How to initialize sliceT? composite literal does not help here..

答案1

得分: 3

使用一个简单的辅助函数:

func str(s string) *string {return &s}

...
m1: str("0000000001"),
...

请注意,这个辅助函数的作用是将字符串转换为指向字符串的指针。在示例中,m1的值被设置为指向字符串"0000000001"的指针。

英文:

Use a simple helper:

func str(s string) *string {return &s}

...
m1: str("0000000001"),
...

huangapple
  • 本文由 发表于 2021年7月17日 06:24:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/68415821.html
匿名

发表评论

匿名网友

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

确定