如何在只有接口示例的情况下初始化对象列表?

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

How to initialize a list of objects given only an interface sample?

问题

我正在使用Google Go编写一个数据库接口。它接受encoding.BinaryMarshaler对象进行保存,并将它们保存为[]byte切片,然后将数据加载到encoding.BinaryUnmarshaler中返回:

func (db *DB) Get(bucket []byte, key []byte, destination encoding.BinaryUnmarshaler) (encoding.BinaryUnmarshaler, error) {

我想实现一次性加载任意长度的encoding.BinaryUnmarshaler切片(例如“从桶X加载所有数据”)。我希望该函数能够加载任意数量的数据对象,而不需要事先知道要加载多少个对象,因此我不希望最终用户传递一个要填充的切片。相反,我使用一个encoding.BinaryUnmarshaler示例对象来了解我要处理的结构:

func (db *DB) GetAll(bucket []byte, sample encoding.BinaryUnmarshaler) ([]encoding.BinaryUnmarshaler, error) {

在编写代码时遇到的问题是,我不确定如何初始化给定对象的新实例,因为我不知道我正在处理的是什么对象,只知道它符合哪个接口。我尝试的方法是:

tmp := new(reflect.TypeOf(sample))

但是这只会导致错误。

在Go中,如何在不知道结构的情况下创建一个新对象,而只有一个示例对象呢?

英文:

I'm writing a database interface in Google Go. It takes encoding.BinaryMarshaler objects to save and saves them as []byte slices, and it loads data into encoding.BinaryUnmarshaler to return it:

func (db *DB) Get(bucket []byte, key []byte, destination encoding.BinaryUnmarshaler) (encoding.BinaryUnmarshaler, error) {

I want to implement being able to load an arbitrary length slice of encoding.BinaryUnmarshalers in one go (for example "load all data from a bucket X"). I want the function to be able to load any number of data objects without knowing beforehand how many objects are to be loaded, so I don't expect the final user to pass me a slice to be filled. Instead, I take a encoding.BinaryUnmarshaler sample object to know what structures I'm dealing with:

func (db *DB) GetAll(bucket []byte, sample encoding.BinaryUnmarshaler) ([]encoding.BinaryUnmarshaler, error) {

The problem I ran into while coding this, is that I'm not sure how to initialize new instances of a given object, since I don't know what object I am dealing with, only what interface it conforms to. What I tried doing was:

tmp:=new(reflect.TypeOf(sample))

but that just caused an error.

How can I create a new object in go without knowing what structure it is, having an example object instead?

答案1

得分: 1

你需要使用reflect.Newreflect.TypeOf来实现:

tmp := reflect.New(reflect.TypeOf(sample))

http://play.golang.org/p/-ujqWtRzaP

英文:

You would have to use reflect.New along with reflect.TypeOf:

tmp := reflect.New(reflect.TypeOf(sample))

http://play.golang.org/p/-ujqWtRzaP

huangapple
  • 本文由 发表于 2015年10月3日 06:14:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/32916619.html
匿名

发表评论

匿名网友

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

确定