dtt78245 2019-06-19 08:30
浏览 201
已采纳

如何使用map [string] * string

I'm trying to use sarama (Admin mode) to create a topic. Without the ConfigEntries works fine. But I need to define some configs.

I set up the topic config (Here is happening the error):

    tConfigs := map[string]*string{
        "cleanup.policy":      "delete",
        "delete.retention.ms": "36000000",
    }

But then I get an error:

./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

I'm trying to use the admin mode like this:

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

Here is the line from the sarama module that defines CreateTopic() https://github.com/Shopify/sarama/blob/master/admin.go#L18

Basically, I didn't understand how the map of pointers strings works :)

  • 写回答

1条回答 默认 最新

  • doujiang2020 2019-06-19 08:39
    关注

    To initialize a map having string pointer value type with a composite literal, you have to use string pointer values. A string literal is not a pointer, it's just a string value.

    An easy way to get a pointer to a string value is to take the address of a variable of string type, e.g.:

    s1 := "delete"
    s2 := "36000000"
    
    tConfigs := map[string]*string{
        "cleanup.policy":      &s1,
        "delete.retention.ms": &s2,
    }
    

    To make it convenient when used many times, create a helper function:

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

    And using it:

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

    Try the examples on the Go Playground.

    See background and other options here: How do I do a literal *int64 in Go?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题