From 25c3f2b3a7c27a5e5915c76b16cac0380f6b14d7 Mon Sep 17 00:00:00 2001 From: Twiink Date: Fri, 27 Nov 2026 20:06:25 +0800 Subject: [PATCH] =?UTF-8?q?fix(builtin):=20=E6=94=AF=E6=8C=81=E5=B0=86?= =?UTF-8?q?=E8=87=AA=E5=AE=9A=E4=B9=89=E6=95=B0=E5=80=BC=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E8=BD=AC=E6=8D=A2=E4=B8=BA=E6=B5=AE=E7=82=B9=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- builtin/lib.go | 11 +++++++++++ expr_test.go | 23 +++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/builtin/lib.go b/builtin/lib.go index 3d45ea586..9d8f5fef3 100644 --- a/builtin/lib.go +++ b/builtin/lib.go @@ -229,6 +229,17 @@ func Float(x any) any { } return f default: + val := reflect.ValueOf(x) + switch val.Kind() { + case reflect.String: + return Float(val.String()) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return float64(val.Int()) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return float64(val.Uint()) + case reflect.Float32, reflect.Float64: + return val.Float() + } panic(fmt.Sprintf("invalid operation: float(%T)", x)) } } diff --git a/expr_test.go b/expr_test.go index 7e2b3eff1..defe14e52 100644 --- a/expr_test.go +++ b/expr_test.go @@ -3238,3 +3238,26 @@ func TestBytesLiteral_errors(t *testing.T) { }) } } + +func TestFloatWithDefinedTypes(t *testing.T) { + type rate float32 + type count uint16 + type delta int64 + type amount string + for _, tt := range []struct { + value any + want float64 + }{ + {rate(1.5), 1.5}, + {count(512), 512}, + {delta(-7), -7}, + {amount("2.75"), 2.75}, + } { + env := map[string]any{"value": tt.value} + program, err := expr.Compile("float(value)", expr.Env(env)) + require.NoError(t, err) + got, err := expr.Run(program, env) + require.NoError(t, err) + require.Equal(t, tt.want, got) + } +}