我使用的是采空区进行序列化结构到磁盘。 有问题的结构包含一个接口领域,所以具体的类型需要使用注册gob.Register(...)
这里的皱纹是图书馆做采空区,ING应该是无知所使用的具体类型。 我想序列化,即使来电者定义自己的接口的实现成为可能。
我可以在飞行中注册类型(见下面简单的例子),但在试图成功地将数据编码重新读取数据,采空区拒绝接受未注册的类型。 它的令人沮丧,因为它感觉像所有的数据都在那里-为什么不采空区刚刚拆包,作为main.UpperCaseTransformation
结构,如果是打成这样?
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)
}
}
我的工作,各地将要求接口的实现者注册它们的采空区类型。 但我不喜欢怎么说我的揭示系列化的选择给市民。
是否有避免这种任何路由转发?