How to convert a 'string pointer' to a string in Golang?

StringPointersGoType Conversion

String Problem Overview


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

String Solutions


Solution 1 - String

Dereference the pointer:

strPointerValue := *strPointer

Solution 2 - String

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 ""
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJared MeyeringView Question on Stackoverflow
Solution 1 - StringOneOfOneView Answer on Stackoverflow
Solution 2 - StringOzanView Answer on Stackoverflow