小白求問。最近在做表示式演算法,發現expr 外掛有人會用嗎、code裡面的all(Tweets, {.Len <= 8}) 和.Len分表代表什麼呢
package main
import "github.com/antonmedv/expr"
type Tweet struct {
Len int
}
type Env struct {
Tweets []Tweet
}
func expt(){
code := `all(Tweets, {.Len <= 8})`
program, err := expr.Compile(code, expr.Env(Env{}))
if err != nil {
panic(err)
}
env := Env{
Tweets: []Tweet{{42}, {98}, {69}},
}
output, err := expr.Run(program, env)
if err != nil {
panic(err)
}
fmt.Println(output)
// 會輸出false
}
已經明白了、非常抱歉佔用大家資源了
env := make(map[string]interface{}, 1<<6)
env["age"] = 0
env["age_new"] = 1
program, err := expr.Compile("age == age_new", expr.Env(env))
if err != nil {
panic(err)
}
output, err := expr.Run(program, env)
if err != nil {
panic(err)
}
fmt.Println(output)
// 輸出 false
func max(a,b interface{} ,i ,j int64) int64{
ta := reflect.TypeOf(a)
tb := reflect.TypeOf(b)
if ta == tb {
if a == b {
return i
} else {
return j
}
} else {
var va, vb float64
switch ta.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64:
va = float64(reflect.ValueOf(a).Int())
case reflect.Float32, reflect.Float64:
va = reflect.ValueOf(a).Float()
default:
return j
}
switch tb.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64:
vb = float64(reflect.ValueOf(b).Int())
case reflect.Float32, reflect.Float64:
vb = reflect.ValueOf(b).Float()
default:
return j
}
if va == vb {
return i
} else {
return j
}
}
return j
}
func qexp(){
env := make(map[string]interface{}, 1<<6)
env["max"] = max
env["age_new"] = 1
env["age_old"] = 12
program, err := expr.Compile("max(age_new,age_old,0,1)", expr.Env(env))
if err != nil {
panic(err)
}
output, err := expr.Run(program, env)
if err != nil {
panic(err)
}
fmt.Println(output)
// 輸出1
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結