遇到 golang 中将值赋给类型指针切片时的无效内存地址问题
时间:2024-03-12
浏览:103
作者:佚名
在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《遇到 golang 中将值赋给类型指针切片时的无效内存地址问题》,聊聊,希望可以帮助到正在努力赚钱的你。
问题内容
在用 go 编写 grpc 服务器时,我有点迷失了这种恐慌
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x1 addr=0x18 pc=0x8c7892]
这就是我正在尝试做的事情,尝试创建测试数据片段:
inputval := make([]*pb.tableheader, 1)
for i := range inputval {
inputval[i].userdefinedalias = "mycustomname"
inputval[i].type = "sometype"
inputval[i].class = "testclass"
inputval[i].columnid = "col12"
inputval[i].issortable = false
inputval = append(inputval, inputval[i])
}
tableheader 具有此结构
type tableheader struct {
columnid string `protobuf:"bytes,1,opt,name=columnid,proto3" json:"columnid,omitempty"`
userdefinedalias string `protobuf:"bytes,2,opt,name=userdefinedalias,proto3" json:"userdefinedalias,omitempty"`
issortable bool `protobuf:"varint,3,opt,name=issortable,proto3" json:"issortable,omitempty"`
type string `protobuf:"bytes,4,opt,name=type,proto3" json:"type,omitempty"`
class string `protobuf:"bytes,5,opt,name=class,proto3" json:"class,omitempty"`
xxx_nounkeyedliteral struct{} `json:"-"`
xxx_unrecognized []byte `json:"-"`
xxx_sizecache int32 `json:"-"`
}
并尝试在 rpc 服务中使用以下内容处理上面创建的测试数据
inputForProcessing := make([]*dt.TableHeader, len(inputVal))
log.Println("reached here for actual processing ",len(inputForProcessing))
for i, v := range inputVal {
inputForProcessing[i].ColumnID = v.ColumnID
inputForProcessing[i].Class = v.Class
inputForProcessing[i].Type = v.Type
inputForProcessing[i].IsSortable = v.IsSortable
inputForProcessing[i].UserDefinedAlias = v.UserDefinedAlias
inputForProcessing = append(inputForProcessing, inputForProcessing[i])
}解决方案
当您调用 inputval := make([]*pb.tableheader, 1) 时,这会创建一个大小为 1 的 *pb.tableheader 切片,但不会执行任何初始化该元素的操作。如果打印出来,您将得到:[<nil>]。
这意味着 for i := range inputval 中的第一次(也是唯一一次)迭代将是 i == 0 且 inputval[i] 将是 nil。尝试在 nil 指针上设置字段会导致您看到的恐慌。
inputforprocessing 也是如此,创建的切片中的所有元素都将为 nil。
此外,您似乎试图将 inputval[i] 附加到 inputval。给定的元素已经存在。
相反,您可能想要以下内容:
inputVal := make([]*pb.TableHeader, 1)
for i := range inputVal {
inputVal[i] = &pb.TableHeader{
UserDefinedAlias: "myCustomName",
Type: "SomeType",
etc...
}
}今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
