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 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥30 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile