Skip to content

expr.AsKind not work? #689

Open
@xtutu

Description

@xtutu
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?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions