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?

Activity

antonmedv

antonmedv commented on Jul 26, 2024

@antonmedv
Member

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

I suspect it is an interface of any?

xtutu

xtutu commented on Jul 29, 2024

@xtutu
Author

@antonmedv

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

antonmedv

antonmedv commented on Jul 30, 2024

@antonmedv
Member

I will take a look.

wodeqiangne

wodeqiangne commented on Aug 2, 2024

@wodeqiangne

I will take a look.

hi,Would you mind if I fixed this issue link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @antonmedv@wodeqiangne@xtutu

      Issue actions

        expr.AsKind not work? · Issue #689 · expr-lang/expr