dourao1968 2019-06-26 08:25
浏览 254
已采纳

使用golang省略函数参数中的数组类型[重复]

This question already has an answer here:

I'm writing a write method, to write an array of value to InfluxDB

What I would like is to be able to have something like:

func (influxClient *InfluxClient) Write(myArray []interface{}) (error) {
    fmt.Print(myArray)
    // Insert into DB
    return nil

}

Where myArray could be an array with any objects inside

I tried to use myArray []interface{} to ommit myArray's type, but it doesn't work, I get:

Cannot use 'meters' (type []models.Meter) as type []interface{}

Is it possible to achieve it ?

How should I do ?

</div>
  • 写回答

2条回答 默认 最新

  • dtn55928 2019-06-26 09:12
    关注

    This happens because []models.Meter and []interface{} are two different types for the Go compiler.

    Using interface{} is not a best-practice typically. It would be better to define your own type and use that instead.

    Having said that, the quickest solution for your case should be to make Write function a variadic one. Like the example below.

    https://play.golang.org/p/KzzFMAjQvRa

    func Write(myArray ...interface{}) (error) {
        fmt.Printf("Slice: %v
    ", myArray)
        // Insert into DB
        return nil
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求红米或者任意工作安卓机ro,ot之后劫c ,h ,i摄像头, 实现无人直播瞒过抖音直播助手的教程, 或者远程 协助也可以。
  • ¥15 elasticsearch
  • ¥30 python ttk 获取下拉框问题
  • ¥15 uniapp的uni-datetime-picker组件在ios端不适配
  • ¥15 前端 uniapp App端在离线状态如何使用modbus 连接手机蓝牙进行读写操控机器?
  • ¥15 SQL语句根据字段自动生成行
  • ¥500 “掌声响起来”软件(不确定性人工智能)
  • ¥500 我要找大模型一体机产品手册和应用案例
  • ¥20 关于游戏c++语言代码问题
  • ¥15 如何制作永久二维码,最好是微信也可以扫开的。(相关搜索:管理系统)