expr icon indicating copy to clipboard operation
expr copied to clipboard

Dynamically constructed []string has type of []interface

Open daisy1754 opened this issue 3 years ago • 1 comments

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
}

daisy1754 avatar Dec 15 '20 22:12 daisy1754

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.

antonmedv avatar Dec 16 '20 08:12 antonmedv

Fixed! Now always []any!

antonmedv avatar Nov 05 '22 19:11 antonmedv