dpeqsfx5186 2016-04-05 14:39
浏览 69

使用通用类型参数在Go中创建函数

I am trying to create a generic function that can accept a key string and a reference to an object.

The function reads a key's content, which is a serialized byte array out of an original object of the same type and it should assign that (deserializing) to an empty structure of that same type. The function wants to be generic, so it can serialize a type A as well as B or []C

Here is what I tried to do:

func GetObject(key string, thing interface{}) error {
    var buf bytes.Buffer        
    dec := gob.NewDecoder(&buf)
    err := dec.Decode(thing)
    if err != nil {
        log.Errorf(cs.ctx, "cloud store - GetObject - decode error:", err)
        return err
    }
    return nil
}

This is how I try to invoke the above function:

newThing := MyStruct{}
err := GetObject("a123", &newThing)

The last lines about cause a runtime error:

decode error:%!(EXTRA *errors.errorString=EOF)

the question:

  • is the interface approach correct for this purpose (allow the function be used generically) ?
  • The serialization error ( using Gob ) seems to be problematic. Any suggestions on how to rectify that ?
  • 写回答

1条回答 默认 最新

  • dswm97353 2016-04-05 15:13
    关注

    The concept of interfaces is correct. The issue was related to a missing getter from the persistence store and how to create a buffer out of its []byte content:

    func GetObject(key string, thing interface{}) error {
        content, _ := SomePersistanceStoreGet(fileName)
        buffer := bytes.NewBuffer(content)
        dec := gob.NewDecoder(buffer)
       err := dec.Decode(thing)
        if err != nil {
            log.Errorf("decode error: %v", err)
            return err
        }
        return nil
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#c语言#的问题:构成555单稳态触发器,采用LED指示灯延时时间,对延时时间进行测量并显示(如楼道声控延时灯)需要Proteus仿真图和C语言代码
  • ¥50 神舟笔记本,没有linux的驱动,装的Ubuntu系统,想把风扇速度调到最大
  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,怎样解决呢?
  • ¥50 如何用单纯形法寻优不能精准找不到给定的参数,并联机构误差识别,给定误差有7个?matlab
  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,没有XFS,怎样解决呢?
  • ¥15 应用商店如何检测在架应用内容是否违规?
  • ¥15 Ubuntu系统配置PX4
  • ¥50 nw.js调用activex
  • ¥15 数据库获取信息反馈出错,直接查询了ref字段并且还使用了User文档的_id而不是自己的
  • ¥15 将安全信息用到以下对象时发生以下错误:c:dumpstack.log.tmp 另一个程序正在使用此文件,因此无法访问