英文:
Issue with serialization and deserialization of map in go lang
问题
我正在进行基本的映射序列化和反序列化,如此示例中所建议的。但是我遇到了以下错误:
panic: EOF
goroutine 1 [running]:
main.load(0x81147e0, 0x1840a378)
/home/naresh/Desktop/Work/GoEventHandler/test.go:39 +0x2cf
main.main()
/home/naresh/Desktop/Work/GoEventHandler/test.go:16 +0xe5
exit status 2
有人能告诉我在下面的代码中我做错了什么吗:
package main
import (
"fmt"
"bytes"
"encoding/gob"
)
func main() {
org := map[string]string{"hello": "world"}
store(org)
var loadedMap map[string]string
load(&loadedMap)
fmt.Println(loadedMap)
}
func store(data interface{}) {
m := new(bytes.Buffer)
enc := gob.NewEncoder(m)
err := enc.Encode(data)
if err != nil {
panic(err)
}
}
func load(e interface{}) {
p := new(bytes.Buffer)
dec := gob.NewDecoder(p)
err := dec.Decode(e)
if err != nil {
panic(err)
}
}
英文:
I am doing the basic serialization and deserialization of map as suggested in this example. But I get the following error:
panic: EOF
goroutine 1 [running]:
main.load(0x81147e0, 0x1840a378)
/home/naresh/Desktop/Work/GoEventHandler/test.go:39 +0x2cf
main.main()
/home/naresh/Desktop/Work/GoEventHandler/test.go:16 +0xe5
exit status 2
Can anyone tell me what I am doing wrong in the following code:
package main
import (
"fmt"
"bytes"
"encoding/gob"
)
func main() {
org := map[string]string{"hello": "world"}
store(org)
var loadedMap map[string]string
load(&loadedMap)
fmt.Println(loadedMap)
}
func store(data interface{}) {
m := new(bytes.Buffer)
enc := gob.NewEncoder(m)
err := enc.Encode(data)
if err != nil {
panic(err)
}
}
func load(e interface{}) {
p := new(bytes.Buffer)
dec := gob.NewDecoder(p)
err := dec.Decode(e)
if err != nil {
panic(err)
}
}
答案1
得分: 4
解码是一个需要编码信息的过程,编码信息将会存储在用于编码的缓冲区中。将其传递给解码器。
package main
import (
"bytes"
"encoding/gob"
"fmt"
)
func main() {
org := map[string]string{"hello": "world"}
buf := store(org)
loadedMap := make(map[string]string)
load(&loadedMap, buf)
fmt.Println(loadedMap)
}
func store(data interface{}) *bytes.Buffer {
m := new(bytes.Buffer)
enc := gob.NewEncoder(m)
err := enc.Encode(data)
if err != nil {
panic(err)
}
return m
}
func load(e interface{}, buf *bytes.Buffer) {
dec := gob.NewDecoder(buf)
err := dec.Decode(e)
if err != nil {
panic(err)
}
}
以上是要翻译的内容。
英文:
Decoding is a process that requires the encoded information which will be in buffer used for encoding. Pass that to the decoder.
package main
import (
"bytes"
"encoding/gob"
"fmt"
)
func main() {
org := map[string]string{"hello": "world"}
buf := store(org)
loadedMap := make(map[string]string)
load(&loadedMap, buf)
fmt.Println(loadedMap)
}
func store(data interface{}) *bytes.Buffer {
m := new(bytes.Buffer)
enc := gob.NewEncoder(m)
err := enc.Encode(data)
if err != nil {
panic(err)
}
return m
}
func load(e interface{}, buf *bytes.Buffer) {
dec := gob.NewDecoder(buf)
err := dec.Decode(e)
if err != nil {
panic(err)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论