expr-lang / expr

Expression language and expression evaluation for Go
https://expr-lang.org
MIT License
6.25k stars 398 forks source link

expr.AsKind not work? #689

Open xtutu opened 3 months ago

xtutu commented 3 months ago
package main

import (
    "errors"
    "fmt"
    "reflect"

    "github.com/expr-lang/expr"
)

type Number interface {
    int | uint | uint32 | int32 | uint64 | int64 | float32 | float64
}

func TryStrToNum[T Number](str string) (retValue T, err error) {
    program, err := expr.Compile(str, expr.AsKind(reflect.TypeOf(retValue).Kind()))
    if err != nil {
        fmt.Printf("Compile Error: %s, %v\n", str, err)
        return
    }
    v, err := expr.Run(program, nil)
    if err != nil {
        fmt.Printf("Run  Error: %s, %v\n", str, err)
        return
    }
    retValue, flag := v.(T)
    if !flag {
        fmt.Printf("StrToNumber Error: %s, %v", str, v)
        return retValue, errors.New(fmt.Sprintf("TryStrToNum error: %s", str))
    }
    return retValue, nil
}

func main() {
    fmt.Println(TryStrToNum[int32]("1")) 
}

/*
Compile Error: 1, expected int32, but got int
0 expected int32, but got int
*/

is it a bug ? How to fix it?

antonmedv commented 3 months ago

What is reflect type of reflect.TypeOf(retValue).Kind()?

I suspect it is an interface of any?

xtutu commented 3 months ago

@antonmedv

when I use: TryStrToNum[int32]("1") reflect.TypeOf(retValue).Kind() is int32

antonmedv commented 3 months ago

I will take a look.

wodeqiangne commented 3 months ago

I will take a look.

hi,Would you mind if I fixed this issue link