在Go语言中创建一个具有通用类型参数的函数。

huangapple go评论61阅读模式
英文:

Creating a function in Go with generic type parameters

问题

我正在尝试创建一个通用函数,可以接受一个键字符串和一个对象的引用。

该函数读取键的内容,该内容是原始对象的序列化字节数组,并将其(反序列化)赋值给相同类型的空结构。该函数希望是通用的,因此可以序列化类型A、B或[]C。

以下是我尝试的代码:

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
}

这是我尝试调用上述函数的方式:

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

关于最后几行会导致运行时错误:

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

问题:

  • 对于这个目的,接口的方法是否正确(允许函数通用使用)?
  • 使用Gob进行序列化时出现问题。有没有关于如何纠正这个问题的建议?
英文:

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

得分: 1

接口的概念是正确的。问题与持久化存储中缺少的getter方法以及如何将其[]byte内容创建为缓冲区有关:

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
}
英文:

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
}

huangapple
  • 本文由 发表于 2016年4月5日 22:39:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/36429554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定