91

Is it possible to get the string value from a pointer to a string?

I am using the goopt package to handle flag parsing and the package returns *string only. I want to use these values to call a function in a map.

Example

var strPointer = new(string)
*strPointer = "string"

functions := map[string]func() {
    "string": func(){
        fmt.Println("works")
    },
}  

//Do something to get the string value

functions[strPointerValue]()

returns

./prog.go:17:14: cannot use strPointer (type *string) 
as type string in map index

3 Answers 3

156

Dereference the pointer:

strPointerValue := *strPointer
Sign up to request clarification or add additional context in comments.

3 Comments

that's correct, however if the pointer string is nil you will have a runtime error
What would be a better solution then?
@ram4nd if strPointer != nil { strPointerValue := *strPointer }
27

A simple function that first checks if the string pointer is nil would prevent runtime errors:

func DerefString(s *string) string {
    if s != nil {
        return *s
    }

    return ""
}

Comments

7

Generic https://stackoverflow.com/a/62790458/1079543 :

func SafeDeref[T any](p *T) T {
    if p == nil {
        var v T
        return v
    }
    return *p
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.