如何初始化仅给定接口样本的对象列表? [英] How to initialize a list of objects given only an interface sample?
问题描述
我正在Google Go中编写数据库界面。它需要 encoding.BinaryMarshaler
对象来保存并保存为[]字节片,并且它将数据加载到 encoding.BinaryUnmarshaler
返回它:
func(db * DB)Get(bucket [] byte,key [] byte,destination encoding。 BinaryUnmarshaler)(encoding.BinaryUnmarshaler,error){
我想实现能够加载任意长度切片 encoding.BinaryUnmarshaler
s一次性完成(例如加载桶X中的所有数据)。我希望函数能够加载任意数量的数据对象,而无需事先知道需要加载多少个对象,所以我不希望最终用户传递一个片段来填充。相反,我使用 encoding.BinaryUnmarshaler
示例对象来了解我正在处理的结构:
func(db * DB)GetAll(bucket [] byte,sample encoding.BinaryUnmarshaler)([] encoding.BinaryUnmarshaler,error){
我在编写这个代码时碰到的问题是我不确定如何初始化给定对象的新实例,因为我不知道我是什么对象只处理它符合的接口。我试过的是:
$ b $ pre $ tmp:= new(reflect.TypeOf(sample))
但是这只是导致一个错误。
如何创建一个新对象在不知道它是什么结构的情况下,是否有一个示例对象?
您必须使用 reflect.New
以及 reflect.TypeOf
:
tmp:= reflect.New(reflect.TypeOf(sample))
http://play.golang.org/p/-ujqWtRzaP
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.BinaryUnmarshaler
s 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?
You would have to use reflect.New
along with reflect.TypeOf
:
tmp := reflect.New(reflect.TypeOf(sample))
http://play.golang.org/p/-ujqWtRzaP
这篇关于如何初始化仅给定接口样本的对象列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!