猿问

当 *string 值为 nil 时,如何将 *string 类型的值转换/分配为

我正在尝试将 type 的值分配给 type*string的变量*wrapperspb.StringValue。但是,当*string为 nil 时,它会触发错误(请查看截取代码中的注释以了解是何种错误)。


这是我的代码的简化版本:


// 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)

}

有谁知道如何正确处理转换/分配?


这是一个 golang 游乐场:https ://go.dev/play/p/5JBfU0oEIC-


大话西游666
浏览 121回答 1
1回答

不负相思意

如果您的var2字符串指针是nil,您也应该保留var1 *wrapperspb.StringValue指针nil。wrapperspb.StringValue如果本身是nil指针,则句柄的方法。所以像这样“转换”它:if var2 == nil {&nbsp; &nbsp; var1 = nil} else {&nbsp; &nbsp; var1 = wrapperspb.String(*var2)}测试它:for i := 0; i < 2; i++ {&nbsp; &nbsp; var var1 *wrapperspb.StringValue&nbsp; &nbsp; var var2 *string&nbsp; &nbsp; if i == 0 {&nbsp; &nbsp; &nbsp; &nbsp; s := "test"&nbsp; &nbsp; &nbsp; &nbsp; var2 = &s&nbsp; &nbsp; }&nbsp; &nbsp; if var2 == nil {&nbsp; &nbsp; &nbsp; &nbsp; var1 = nil&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; var1 = wrapperspb.String(*var2)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Printf("var2: %v\n", var2)&nbsp; &nbsp; fmt.Printf("var1: %v\n", var1)&nbsp; &nbsp; fmt.Printf("%q\n", var1.GetValue())}这将输出(在Go Playground上尝试):var2: 0xc00009e470var1: value:"test""test"var2: <nil>var1: <nil>""
随时随地看视频慕课网APP

相关分类

Go
我要回答