It's not possible to get the address (to point) of a constant value, which is why your initialization fails. If you define a variable and pass its address, your example will work.

type Config struct {
  Uri       *string
}

func init() {
  v := "my:default"
  var config = Config{ Uri: &v }
}
Answer from Nadh on Stack Overflow
🌐
GitHub
github.com › golang › go › issues › 63309
proposal: strings: Create a string pointer from string constant · Issue #63309 · golang/go
September 30, 2023 - When we want to pass a string pointer to a struct member each time we have to create a separate variable and pass the address of that to the member variable, Which is a pain. This wrapper function will ease all those efforts. Eg: type Em...
Published   Sep 30, 2023
🌐
Dhdersch
dhdersch.github.io › golang › 2016 › 01 › 23 › golang-when-to-use-string-pointers.html
GoLang: When to use string pointers
If it is acceptable for a missing property to be unmarshalled into an empty string, then there is no problem. In other words, if you will handle missing json properties and empty json properties the same, then use a normal string. But what if "" is a valid configuration value for HostName, but a missing property is not valid? Answer: use a *string. package main import ( "encoding/json" "fmt" ) type ConfigWithPointers struct { Environment *string // pointer to string Version *string HostName *string } func (c *ConfigWithPointers) String() string { var envOut, verOut, hostOut string envOut = "<nil>" verOut = "<nil>" hostOut = "<nil>" if c.Environment != nil { // Check for nil!
🌐
Go Forum
forum.golangbridge.org › getting help
Pointer to struct vs Pointer to string - Getting Help - Go Forum
April 4, 2018 - Hi guys ! I am new to Golang. I just can’t understand and self-explain this code. type Book struct { name string } func main() { a := &Book{name: “hehe”} b := &string(“hehe”) fmt.Println(a) // Why work? fmt.Prin…
🌐
Google Groups
groups.google.com › g › golang-nuts › c › InAPIyouzPE
convert string to *string
On Wed, Oct 07, 2015 at 03:25:41AM ... in database) https://golang.org/pkg/database/sql/#NullString Strings in go are immutable, so a string value is kinda-sorta already like a pointer....
🌐
Reddit
reddit.com › r/golang › when to use string pointers in go
r/golang on Reddit: When to use string pointers in Go
January 21, 2015 - This way, failure to check the validity of some OptionalString could yield "", to keep the program from panicking. ... What about function calls? Do naked strings get copied if the parameter isn't modified by the function? I.e. which one is faster: ... worrying about this is a massive over optimization. the compiler is smarter than you; let it do its job and just write readable, bug-free code. don't use a pointer just because you think it will make things faster.
🌐
Reddit
reddit.com › r/golang › can someone explain why string pointers are like this?
r/golang on Reddit: Can someone explain why string pointers are like this?
April 10, 2025 -

Getting a pointer to a string or any builtin type is super frustrating. Is there an easier way?

attempt1 := &"hello"              // ERROR
attempt2 := &fmt.Sprintf("hello") // ERROR
const str string = "hello"
attempt3 = &str3                  // ERROR
str2 := "hello"
attempt4 := &str5

func toP[T any](obj T) *T { return &obj }
attempt5 := toP("hello")

// Is there a builting version of toP? Currently you either have to define it
// in every package, or you have import a utility package and use it like this:

import "utils"
attempt6 := utils.ToP("hello")
🌐
Reddit
reddit.com › r/golang › aws.string, pointers, etc. explained?
r/golang on Reddit: aws.String, Pointers, etc. Explained?
January 30, 2024 -

Context: https://github.com/aws/aws-sdk-go/issues/363

I came upon this while wondering why we have to use aws.String("xx") in aws go api calls.

The top answer starts with:

The aws.String is a helper so literal strings can be used when 
setting API field pointer values without needing to define a local 
variable first, because &"xxx" is not valid syntax. If the value is 
already defined as a local variable &xxxStr can also be used."

This part makes sense, you can't use a pointer to a literal string, it needs to be declared as a var (is there a name for this specifically?), as &"mystringhere" is not valid syntax, but rather a := "mystringhere", then &a.

However the next portion confuses me:

The AWS API operations include many optional fields which should not be included in the marshaled request if not set. In order to represent the ternary state for these fields pointers are used. This is done because it is not possible to distinguish between a never set value from a value set to the type's Zero value. The SDK uses pointers for all primitive and struct type fields. In many cases the type's Zero value of a field has meaning, and is different from unset, and a non zero value. All API fields in Input and Output structs are pointers, because even though a field is required today, it may not be required in the future. A breaking change would be required to allow not setting the once required field.

Can anyone explain this in semi non-go/programming terms? I'm trying to go through it step by step:

Calls to AWS APIs have optional fields that shouldn't be included in the request if they are not set

This means that vars that are not set, and thus have a nil or empty value, should not be sent in the request?

...Ternary state is represented by pointer...

This is just saying that the value passed to the API call is a pointer because there needs to be some flat value to pass to the API because go represents unset vars in different ways per type?

All API fields in Input and Output structs are pointers, because even though a field is required today, it may not be required in the future.

Everything passed to these API calls are pointers so that changes in the future don't break client code, and are handled on the AWS backend.

Find elsewhere
🌐
GitHub
github.com › golang › go › issues › 45624
spec: expression to create pointer to simple types · Issue #45624 · golang/go
April 19, 2021 - (Latest proposal at #45624 (comment); --adonovan) This notion was addressed in #9097, which was shut down rather summarily. Rather than reopen it, let me take another approach. When &S{} was added to the language as a way to construct a ...
Published   Apr 19, 2021
🌐
Ronald James
ronaldjamesgroup.com › article › the-proper-use-of-pointers-in-go-golang
The Proper Use of Pointers in Go (golang) | Ronald James
Many developers that are new to the language, or new to a language that can handle memory directly using pointers end up misusing those pointers. A pointer is a variable that stores the address of a value, rather than the value itself. If you think of a computer’s memory (RAM) as a JSON object, a pointer would be like the key, and a normal variable would be the value. ... package main import "fmt" func main() { // create a normal string variable name := "original" // pass in a pointer to the string variable using '&' setName(&name, "qvault") fmt.Println(name) } func setName(ptr *string, newName string) { // dereference the pointer so we can modify the value // and set the value to "qvault" *ptr = newName }
🌐
Google Groups
groups.google.com › g › golang-nuts › c › 2MzMl_sff4E
Assign to String Pointer
I am having to use a string pointer type because my struct is being unmarshalled using encoding/json and if the incoming string is null, JSON requires a string pointer to correctly unmarshall the value. I think that JSON is using reflection to populate the string pointer but I want to be able to set and manipulate the string pointer from regular Go code without using reflection.
🌐
Medium
medium.com › analytics-vidhya › pointers-in-golang-1a679b464849
Pointers in Golang. Pointers are a very basic but extremely… | by Rene Manqueros | Analytics Vidhya | Medium
May 31, 2021 - On myFunctionWithPointers: the star/asterisk ( * ), will tell Go: we are going to receive a pointer with the data type of a string, it is very important to note that pointers need a type, pointer to an int, pointer to a string, pointer to a ...
🌐
Go Packages
pkg.go.dev › k8s.io › utils › pointer
pointer package - k8s.io/utils/pointer - Go Packages
IntPtrDerefOr is a function variable referring to IntDeref. Deprecated: Use ptr.Deref instead. ... String returns a pointer to a string.
🌐
GeeksforGeeks
geeksforgeeks.org › pointers-in-golang
Pointers in Golang - GeeksforGeeks
In this article,we will learn different ... s2 : ... Pointers in Go programming language or Golang is a variable that is used to store the memory address of another variable....
Published   August 11, 2021
🌐
Go Forum
forum.golangbridge.org › getting help
How to convert primitive types to pointers in a common way in Golang? - Getting Help - Go Forum
September 1, 2024 - I know in Golang it uses & to get a pointer of a variable, not for a constant: // incorrect a := &"test" For this suituation, we need to define an extra variable explicity: // correct str := "test" a := &str I try to define a function to do the converting for every type: func PStr(s string) *string { return &s } func PInt(s int) *int { return &s } a := &PStr("test") I thought of converting all primitive types to a pointer using generic: type BasicType interface { ~string | ~bool | ~int...
🌐
DEV Community
dev.to › adriandy89 › golang-pointers-and-functions-a-guide-with-examples-1paj
Golang Pointers and Functions: A Guide with Examples - DEV Community
May 17, 2023 - This function takes a pointer to a string variable as its argument. Inside the function, we use the "*" operator to dereference the pointer and access the value of the variable it points to.
🌐
Boot.dev
blog.boot.dev › golang › the-proper-use-of-pointers-in-go-golang
The Proper Use of Pointers in Go (Golang) | Boot.dev
September 25, 2019 - Many developers that are new to the language, or new to a language that can handle memory directly using pointers end up misusing those pointers. A pointer is a variable that stores the address of a value, rather than the value itself. If you think of a computer’s memory (RAM) as a JSON object, a pointer would be like the key, and a normal variable would be the value. ... package main import "fmt" func main() { // create a normal string variable name := "original" // pass in a pointer to the string variable using '&' setName(&name, "boot.dev") fmt.Println(name) } func setName(ptr *string, newName string) { // dereference the pointer so we can modify the value // and set the value to "boot.dev" *ptr = newName }
Top answer
1 of 5
25

Taking the address of a literal (string, number, etc) is illegal because it has ambiguous semantics.

Are you taking the address of the actual constant? Which would allow the value to be modified (and could lead to a runtime error) or do you want to allocate a new object, copy the constant over and get the address to the new version?

This ambiguity does not exist in the case of test2 since you are dealing with an existing variable of which the semantics are clearly defined. The same would not work if the string was defined as const.

The language spec avoids this ambiguity by explicitly not allowing what you are asking for. The solution is test2. While it is slightly more verbose, it keeps the rules simple and clean.

Of course, every rule has its exceptions, and in Go this concerns composit literals: The following is legal and defined as such in the spec:

func f() interface{} {
    return &struct {
        A int
        B int
    }{1, 2} 
}
2 of 5
22

For the question of the best solution for your situation of passing around "static" strings,

  1. Pass the string type instead of *string.
  2. Don't make assumptions about what is going on behind the scenes.

It's tempting to give the advice "don't worry about allocating strings" because that's actually true in the case you're describing where the same string is passed around, perhaps many times. It general though, it's really good to think about memory use. It's just really bad to guess, and even worse to guess based on experience with another language.

Here's a modified version of your program. Where do you guess that memory is allocated?

package main

import "fmt"

var konnichiwa = `こんにちは世界`

func test1() *string {
    s := `Hello world`
    return &s
}

func test2() string {
    return `Hej världen`
}

func test3() string {
    return konnichiwa
}

func main() {
    fmt.Println(*test1())
    fmt.Println(test2())
    fmt.Println(test3())
}

Now ask the compiler:

> go tool 6g -S t.go

(I named the program t.go.) Search the output for calls to runtime.new. There's only one! I'll spoil it for you, it's in test1.

So without going off on too much of a tangent, the little look at the compiler output indicates that we avoid allocation by working with the string type rather than *string.