How to convert a 'string pointer' to a string in Golang?
68,856
Solution 1
Dereference the pointer:
strPointerValue := *strPointer
Solution 2
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
-
Jared Meyering almost 2 years
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.
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
-
Matteo over 4 yearsthat's correct, however if the pointer string is
nil
you will have a runtime error -
ram4nd over 4 yearsWhat would be a better solution then?
-
Archie Yalakki over 3 years@ram4nd if strPointer != nil { strPointerValue := *strPointer }