Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set nil string pointer to empty string

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?

like image 437
Jimmy P Avatar asked Jun 04 '17 23:06

Jimmy P


People also ask

Can a string be nil?

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.

How do you declare an empty string in Golang?

The zero value is: 0 for numeric types, false for the boolean type, and. "" (the empty string) for strings.

What is the empty string in C?

An empty string ( "" ) consists of no characters followed by a single string terminator character - i.e. one character in total.

How do I check if a string is nil in Swift?

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.


1 Answers

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)
like image 193
Bayta Darell Avatar answered Sep 30 '22 18:09

Bayta Darell