How do I set the referenced value of a string pointer in a type to the empty string? Consider this example:
package main
import (
"fmt"
)
type Test struct {
value *string
}
func main() {
t := Test{nil}
if t.value == nil {
// I want to set the pointer's value to the empty string here
}
fmt.Println(t.value)
}
I've tried all combinations of the &
and *
operators to no avail:
t.value = &""
t.value = *""
&t.value = ""
*t.value = ""
Obviously some of those are silly, but I didn't see the harm in trying.
I also tried using reflect
and SetString
:
reflect.ValueOf(t.value).SetString("")
and this gives a compilation error
panic: reflect: reflect.Value.SetString using unaddressable value
I'm assuming that's because strings in Go are immutable?
A string cannot be nil, because the data structure in go doesn't allow it. You can have a pointer to a byte array holding character representations in go be null, but that isn't a string.
The zero value is: 0 for numeric types, false for the boolean type, and. "" (the empty string) for strings.
An empty string ( "" ) consists of no characters followed by a single string terminator character - i.e. one character in total.
Using the guard statement This unwraps the optional string and checks that it isn't empty all at once. If it is nil (or empty), then you return from your function (or loop) immediately and everything after it is ignored. But if the guard statement passes, then you can safely use your unwrapped string.
String literals are not addressable.
Take the address of variable containing the empty string:
s := ""
t.value = &s
or use new:
t.value = new(string)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With