Set the parameter as an interface or a list of interfaces
I am new to Go and there are some utilities that I am not getting yet
For example, I have a function that can be called like this:
myVar.InitOperation("foo",Operator.EQUAL,"bar")
myVar.InitOperation("foo",Operator.INCLUDE,[]interface{}{"baz",1,"boo"})
myVar.InitOperation("foo",Operator.GREATER_THAN,1)
So, I declared this function as:
func InitOperation(attr string, operator Operator, value interface{}){
if operator.String() == "BAR"{
doSomething(attr,operator,value)
} else if (operator.String() == "INCLUDE" {
doSomethingElse(attr,operator,value)
}
// And so on regarding to the case
}
The thing is, when I pass in a string or an integer it happens fine, but when I pass in an array, it is parsed as one element.
In my function, doSomethingElse
I'm trying to iterate over values
, and as you can guess, I have a bug.
Ok, I just installed values
as []interface{}
, not interface{}
. Everything goes well here, but when I call doSomething
it is parsed as [[myValue]]
, which is logical, but not what I expect.
My question is, is there a way to pass either []interface{}
, interface{}
which can be red as a value or an array of relevant values?
Thank!
source to share
You need a type assertion:
func InitOperation(attr string, operator Operator, value interface{}){
if operator.String() == "BAR"{
doSomething(attr,operator,value)
} else if (operator.String() == "INCLUDE" {
doSomethingElse(attr, operator, value.([]interface{}))
}
// And so on regarding to the case
}
func doSomethingElse(attr string, operator Operator, value []interface{}) {
for _, v := range value {
fmt.Println(v)
}
}
source to share