I am trying to assign a value with type *string
to a variable with type *wrapperspb.StringValue
. However, when the *string
is nil, it triggers an error (please see the comments in the snipped code to see what kind of error).
Here is a simplified version of my code:
// You can edit this code!
// Click here and start typing.
package main
import (
"fmt"
"google.golang.org/protobuf/types/known/wrapperspb"
)
func main() {
var var1 *wrapperspb.StringValue
var1 = &wrapperspb.StringValue{Value: "test1"}
fmt.Println("var1:")
fmt.Println(var1)
var var2 *string
fmt.Println("var2:")
fmt.Println(var2)
//var1 = var2 // it says "Cannot use 'var2' (type *string) as the type *wrapperspb.StringValue"
//var1 = wrapperspb.String(*var2) // it says panic: runtime error: invalid memory address or nil pointer dereference
//fmt.Println("var1 with var2 value:")
//fmt.Println(var1)
}
Does anyone know how to properly handle the conversion/assignment?
Here is a golang playground: https://go.dev/play/p/5JBfU0oEIC-
CodePudding user response:
If your var2
string pointer is nil
, you should also leave the var1
*wrapperspb.StringValue
pointer nil
as well. Methods of wrapperspb.StringValue
handles if itself is the nil
pointer. So "convert" it like this:
if var2 == nil {
var1 = nil
} else {
var1 = wrapperspb.String(*var2)
}
Testing it:
for i := 0; i < 2; i {
var var1 *wrapperspb.StringValue
var var2 *string
if i == 0 {
s := "test"
var2 = &s
}
if var2 == nil {
var1 = nil
} else {
var1 = wrapperspb.String(*var2)
}
fmt.Printf("var2: %v\n", var2)
fmt.Printf("var1: %v\n", var1)
fmt.Printf("%q\n", var1.GetValue())
}
This will output (try it on the Go Playground):
var2: 0xc00009e470
var1: value:"test"
"test"
var2: <nil>
var1: <nil>
""