Home > front end >  Easy way to get string pointers
Easy way to get string pointers

Time:08-05

A library I am using has a very weird API that often takes string pointers. Currently I am doing this:

s := "foobar"
weirdFun(&s)

to pass strings. Is there a way to do this without the variable?

CodePudding user response:

Maybe you should inform the author of the library, that the strings in Go are already references (to a structure, which is internally represented as a slice of runes), so no expensive copy operation is made by passing string to a function, it's call by reference. Hope this helps!

CodePudding user response:

The address operation &x can be used with addressable values. According to the language specification:

The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a (possibly parenthesized) composite literal.

So, you can work around this using a composite literal:

package main

import (
    "fmt"
)

func main() {
    s := "text"
    fmt.Printf("value: %v, type: %T\n", &s, &s)
    fmt.Printf("value: %v, type: %T\n", &[]string{"literal"}[0], &[]string{"literal"}[0])
}

Even though it's possible I don't recommend using this. This is not an example of clear code.

CodePudding user response:

The Azure SDK uses string pointers to distinguish between no value and the empty string.

Use Azure's StringPtr function to create a pointer to a string literal.

import (
    ⋮
    "github.com/Azure/go-autorest/autorest/to"
)

⋮
res, err := someClient.Create(ctx, someService.ExampleParameters{
    Location: to.StringPtr(location),
})

CodePudding user response:

The library is really weird, but you can do this in one line with function wrap, for example

func PointerTo[T ~string](s T) *T {
    return &s
}

s := "string"

weirdFun(PointerTo(s))
  • Related