go - 尝试使用指针字段初始化结构时出现nil指针取消引用错误

标签 go null

定义的结构类型:

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

Address operators

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/

相关文章:

go - Golang语法错误:分配不匹配:4个变量但2个值

c# - 为什么在检查空值后从 OdbcDataReader 读取值时会出现 InvalidCastException?

MYSQL 加载数据文件

mysql - 为什么连接到 Google Cloud SQL 在 Docker 容器内失败但在 Docker 容器外成功?

c# - 了解 C# 泛型和 Nullable 值类型。返回 null 或 nullable

java - 使用 Optional.orElseGet() 返回 null 并设置响应值

java - 通过 URL 获取 HTML

go - 我的 Golang 应用程序中是否需要一个或多个 sarama.SyncProducer?

go - 对于上下文而言,取消如此强制吗?

json - Axios PUT请求无效,但GET有效