expr
expr copied to clipboard
Dynamically constructed []string has type of []interface
I want to implement an expression that returns slice of string. expr properly gives []string
when it's immediate value eg ["a"]
but when I do something like [str]
it gives type []interface
even though str is string. Below is code to reproduce behaviour. Ideally I want all cases below to return []string
package main
import (
"fmt"
"github.com/antonmedv/expr"
)
func main() {
env := map[string]interface{}{
"arr": []string{"a","b"},
"s": "s",
}
p1, _ := expr.Compile(`arr`, expr.Env(env))
o1, _ := expr.Run(p1, env)
fmt.Printf("%T", o1) // []string
p2, _ := expr.Compile(`[arr[0]]`, expr.Env(env))
o2, _ := expr.Run(p2, env)
fmt.Printf("%T", o2) // []interface
p3, _ := expr.Compile(`["a"]`, expr.Env(env))
o3, _ := expr.Run(p3, env)
fmt.Printf("%T", o3) // []string
p4, _ := expr.Compile(`[s]`, expr.Env(env))
o4, _ := expr.Run(p4, env)
fmt.Printf("%T", o4) // []interface
}
Currently expr constructs [] as interface. In case of using ["a"]
there is optimisation which replaces it with precomputed constant and alter type.
Maybe this. An be extended to alter type in case of string vars too.
Fixed! Now always []any
!