如何使用map [string] * string

Leo*_*ejo 1 string dictionary pointers go sarama

我正在尝试使用sarama(管理员模式)创建主题。如果没有ConfigEntries,则可以正常运行。但是我需要定义一些配置。

我设置了主题配置(这里发生了错误):

    tConfigs := map[string]*string{
        "cleanup.policy":      "delete",
        "delete.retention.ms": "36000000",
    }
Run Code Online (Sandbox Code Playgroud)

但是然后我得到一个错误:

./main.go:99:28: cannot use "delete" (type string) as type *string in map value
./main.go:100:28: cannot use "36000000" (type string) as type *string in map value
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用这样的管理模式:

err = admin.CreateTopic(t.Name, &sarama.TopicDetail{
    NumPartitions:     1,
    ReplicationFactor: 3,
    ConfigEntries:     tConfigs,
}, false)
Run Code Online (Sandbox Code Playgroud)

这是sarama模块中定义CreateTopic()的代码行, 网址为https://github.com/Shopify/sarama/blob/master/admin.go#L18

基本上,我不了解指针字符串的映射是如何工作的:)

icz*_*cza 5

string使用复合文字初始化具有指针值类型的映射,必须使用string指针值。一个string文字是不是指针,它只是一个string值。

一种获取string值指针的简单方法是获取string类型变量的地址,例如:

s1 := "delete"
s2 := "36000000"

tConfigs := map[string]*string{
    "cleanup.policy":      &s1,
    "delete.retention.ms": &s2,
}
Run Code Online (Sandbox Code Playgroud)

为了方便多次使用,请创建一个辅助函数:

func strptr(s string) *string { return &s }
Run Code Online (Sandbox Code Playgroud)

并使用它:

tConfigs := map[string]*string{
    "cleanup.policy":      strptr("delete"),
    "delete.retention.ms": strptr("36000000"),
}
Run Code Online (Sandbox Code Playgroud)

Go Playground上尝试示例。

在此处查看背景和其他选项:如何在Go中执行文字* int64?