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

使用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>

图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 在这里有答案:

  • 对接口切片进行类型转换 5个答案

    我正在写一个write方法,将值数组写入InfluxDB < p>我想要的是这样的东西:

      func(influxClient * InfluxClient)Write(myArray [] interface {})(错误){
      fmt.Print(myArray)
     //插入数据库
    返回nil 
     
    } 
       
     
     

    其中 myArray 一个数组,里面有任何对象

    我尝试使用 myArray [] interface {} 来省略myArray的类型,但是它不起作用,我得到:< / p >

     不能将'meters'(类型[] models.Meter)用作类型[] interface {} 
       
     
     

    有可能实现吗?

    我应该怎么做?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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
    
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doujiao3016 2019-06-26 10:18

    It is possible if you copy first to an []interface instance

    func main() {
    
       // Copy from your explicit type array
       var interfaceSlice []interface{} = make([]interface{}, len(models.Meter))
    
       for i, Modelvalue := range models.Meter {
           interfaceSlice[i] = Modelvalue
       }    
    
       influxClient.Write(interfaceSlice)
    }
    

    Wiki Interface slice and arrays

    Playground sample

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题