2

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 :)

icza
  • 389,944
  • 63
  • 907
  • 827
BigLeo
  • 6,906
  • 2
  • 13
  • 12
  • 2
    The error is pretty clear. You can't use a string as a pointer to string. What part is unclear? – Jonathan Hall Jun 19 '19 at 08:32
  • I'm new to golang :) I didn't get yet how pointer string works. I understand that a pointer is pointing directly to the value in memory of a variable. But I don't understant what is a map of pointers strings. Should I create a var test string Then point to this var like *test? – BigLeo Jun 19 '19 at 08:55
  • 2
    Okay. I suggest starting with [A Tour of Go](https://tour.golang.org/). Specifically [the section on pointers](https://tour.golang.org/moretypes/1). – Jonathan Hall Jun 19 '19 at 08:58

1 Answers1

7

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?

icza
  • 389,944
  • 63
  • 907
  • 827