-2

在 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])
    }
4

1 回答 1

0

当您调用 时inputVal := make([]*pb.TableHeader, 1),这会创建一个大小为 1 的切片*pb.TableHeader,但不会初始化该元素。如果你打印出来,你会得到:[<nil>].

这意味着第一次(也是唯一一次)迭代for i := range inputVal将是 withi == 0inputVal[i]will be 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...
        }
    }
于 2020-05-08T14:55:39.743 回答