gpt4 book ai didi

pointers - Gob 无法使用 nil 指针值对 map 进行编码

转载 作者:IT王子 更新时间:2023-10-29 01:57:02 25 4
gpt4 key购买 nike

如果其中一个值为 nil,当我尝试将映射编码为指针时,Gob 的编码返回错误。这似乎与文档相矛盾(但我可能误解了意思):

In slices and arrays, as well as maps, all elements, even zero-valued elements, are transmitted, even if all the elements are zero.

代码:

package main

import (
"bytes"
"encoding/gob"
)

type Dog struct {
Name string
}

func main() {
m0 := make(map[string]*Dog)
m0["apple"] = nil

// Encode m0 to bytes
var network bytes.Buffer
enc := gob.NewEncoder(&network)
err := enc.Encode(m0)
if err != nil {
panic(err) // Output: panic: gob: encodeReflectValue: nil element
}
}

输出:

panic: gob: encodeReflectValue: nil element

在这种情况下 gob 失败是否有充分的理由?似乎两个明显的选项中的任何一个都比失败更可取:1)不要使用零值的值对任何键进行编码或 2)即使值是零值也对所有键进行编码。就目前的情况而言,最好的做法是递归扫描我的结构以查看是否有任何 nil 映射值,如果有则删除这些键?如果需要进行此检查,似乎应该由 encoding/gob 包负责,而不是用户。

此外,规则不仅仅是“gob 不能对键值为 nil 的映射进行编码”,因为如果值类型是 slice ,则接受 nil:

func main() {
m0 := make(map[string][]string)
m0["apple"] = nil

// Encode m0 to bytes
var network bytes.Buffer
enc := gob.NewEncoder(&network)
err := enc.Encode(m0) // err is nil
if err != nil {
panic(err) // doesn't panic
}
}

最佳答案

gob 编码流没有指针的概念。如果对指针值进行编码,如*int,则将发送指向的值,即int类型的值。如果需要,这种转换在解码器端被逆转,例如如果在要为其设置 *int 值的流中找到 int 值,则指针(*int 类型)将被设置为指向解码后的 int 值。

因此,如果指针值本身是 nil,则 gob 包无法编码代替指针值的值,即 nil 指针没有指向任何东西。取消引用 nil 指针是运行时 panic 。

这也记录在 gob: Basics:

Pointers are not transmitted, but the things they point to are transmitted; that is, the values are flattened. Nil pointers are not permitted, as they have no value.

关于pointers - Gob 无法使用 nil 指针值对 map 进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50725102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com