Skip to content

expr.AsKind not work? #689

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
xtutu opened this issue Jul 26, 2024 · 4 comments · May be fixed by #693
Open

expr.AsKind not work? #689

xtutu opened this issue Jul 26, 2024 · 4 comments · May be fixed by #693

Comments

@xtutu
Copy link

xtutu commented Jul 26, 2024

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
Copy link
Member

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

I suspect it is an interface of any?

@xtutu
Copy link
Author

xtutu commented Jul 29, 2024

@antonmedv

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

@antonmedv
Copy link
Member

I will take a look.

@wodeqiangne wodeqiangne linked a pull request Aug 2, 2024 that will close this issue
@wodeqiangne
Copy link

I will take a look.

hi,Would you mind if I fixed this issue link

# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants