-1

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 ?

underscore_d
  • 6,309
  • 3
  • 38
  • 64
Juliatzin
  • 18,455
  • 40
  • 166
  • 325
  • if you try to formating a slice of something to a slice of interface, you should maybe have a look [here](https://stackoverflow.com/questions/12753805/type-converting-slices-of-interfaces-in-go) – charles Lgn Jun 26 '19 at 08:51

2 Answers2

1

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\n", myArray)
    // Insert into DB
    return nil

}
Giulio Micheloni
  • 1,290
  • 11
  • 25
0

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

Mario
  • 158
  • 10