duanjiongzhen2523 2016-09-17 04:03
浏览 356
已采纳

Go:接口作为返回值

I have several structs which I fill with data from MongoDB.

type Dog struct {
    Id string
    Age int
}

type Invoice struct {
    Id int
    Amount float
}

I was trying to make a function like this:

func LookUp(collection string, ids []string) []interface{} {
         // Is in cache?
         // if not get them from database
    }

This way i could do something like:

 func GoodDogs() []string{
             // Give the ids of good dogs
        }

 dogsIds := GoodDogs()
 dogs := LookUp("Dogs", namesToRetrieve)

I know i could write the same function over and over for each struct, setting the correct return type and id type (notice some are int, some strings) but... seems too anti DRY.

Interfaces seem to work the other way, for the inputs. Is there a way to do what I'm trying? Or is this is just a wrong design pattern?

  • 写回答

2条回答 默认 最新

  • duanhe4267 2016-09-17 05:31
    关注

    Pass a pointer to the sice as an argument:

    func LookUp(collection string, ids []string, result interface{}) error {
         // Is in cache?
         // if not get them from database
         return db.C(collection).Find(bson.M{"_id": bson.M{"$in": ids}}).All(result)
    }
    

    Call it like this:

    var dogs []*Doc
    err := Lookup("dog", dogIds, &dogs)
    if err != nil 
       // handle error
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛