定义的结构类型:
type ValidateTemplateQuery struct {
TemplateURL *string `json:"template_url" valid:"optional"`
TemplateBody *string `json:"template_body" valid:"optional"`
}
尝试使用模拟值初始化:
action := &ValidateTemplateQuery{
TemplateURL: *("TemplateURLValue"),
TemplateBody: *("TemplateBodyValue"),
}
错误
getting "panic: runtime error: invalid memory address or nil pointer dereference"
最佳答案
trying to initiate with mock values
使用变量的地址。例如,
package main
import (
"fmt"
)
func main() {
type ValidateTemplateQuery struct {
TemplateURL *string `json:"template_url" valid:"optional"`
TemplateBody *string `json:"template_body" valid:"optional"`
}
url := "TemplateURLValue"
body := "TemplateBodyValue"
action := &ValidateTemplateQuery{
TemplateURL: &url,
TemplateBody: &body,
}
fmt.Println(action, *action.TemplateURL, *action.TemplateBody)
}
游乐场:https://play.golang.org/p/LZKV2LZ4KiE
输出:
&{0x40c138 0x40c140} TemplateURLValue TemplateBodyValue
The Go Programming Language Specification
For an operand x of type T, the address operation &x generates a pointer of type *T to x. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a (possibly parenthesized) composite literal. If the evaluation of x would cause a run-time panic, then the evaluation of &x does too.
关于go - 尝试使用指针字段初始化结构时出现nil指针取消引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57933297/