我正在使用 gob 将结构序列化到磁盘。有问题的结构包含一个接口字段,因此需要使用 注册具体类型gob.Register(...)
。
这里的问题是,进行 gob-ing 的库应该不知道所使用的具体类型。即使调用者定义了自己的接口实现,我也希望序列化成为可能。
我可以通过动态注册类型来成功编码数据(参见下面的简单示例),但是在尝试重新读取该数据时,gob 拒绝接受未注册的类型。令人沮丧,因为感觉所有数据都在那里 -main.UpperCaseTransformation
如果它被标记为这样,为什么 gob 不将其解压缩为结构?
package main
import (
"encoding/gob"
"fmt"
"os"
"strings"
)
type Transformation interface {
Transform(s string) string
}
type TextTransformation struct {
BaseString string
Transformation Transformation
}
type UpperCaseTransformation struct{}
func (UpperCaseTransformation) Transform(s string) string {
return strings.ToUpper(s)
}
func panicOnError(err error) {
if err != nil {
panic(err)
}
}
// Execute this twice to see the problem (it will tidy up files)
func main() {
file := os.TempDir() + "/so-example"
if _, err := os.Stat(file); os.IsNotExist(err) {
tt := TextTransformation{"Hello, World!", UpperCaseTransformation{}}
// Note: didn't need to refer to concrete type explicitly
gob.Register(tt.Transformation)
f, err := os.Create(file)
panicOnError(err)
defer f.Close()
enc := gob.NewEncoder(f)
err = enc.Encode(tt)
panicOnError(err)
fmt.Println("Run complete, run again for error.")
} else {
f, err := os.Open(file)
panicOnError(err)
defer os.Remove(f.Name())
defer f.Close()
var newTT TextTransformation
dec := gob.NewDecoder(f)
// Errors with: `gob: name not registered for interface: "main.UpperCaseTransformation"'
err = dec.Decode(&newTT)
panicOnError(err)
}
}
我的解决方法是要求接口的实现者向 gob 注册他们的类型。但我不喜欢这如何向调用者揭示我的序列化选择。
有没有避免这种情况的前进路线?