From 181d2ad2b46aaf5fd48e487405560191b83e45b1 Mon Sep 17 00:00:00 2001 From: Damian Gryski Date: Fri, 24 Mar 2023 10:43:19 -0700 Subject: [PATCH] reflect: add CanInt() and friends and uncomments tests that pass --- src/reflect/all_test.go | 4 ++-- src/reflect/value.go | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/reflect/all_test.go b/src/reflect/all_test.go index b21abfef..895faac3 100644 --- a/src/reflect/all_test.go +++ b/src/reflect/all_test.go @@ -430,6 +430,8 @@ func TestMapIterSet(t *testing.T) { } } +*/ + func TestCanIntUintFloatComplex(t *testing.T) { type integer int type uinteger uint @@ -617,8 +619,6 @@ func TestCanSetField(t *testing.T) { } } -*/ - var _i = 7 var valueToStringTests = []pair{ diff --git a/src/reflect/value.go b/src/reflect/value.go index dbe487f8..ccdd427c 100644 --- a/src/reflect/value.go +++ b/src/reflect/value.go @@ -250,6 +250,16 @@ func (v Value) Bool() bool { } } +// CanInt reports whether Uint can be used without panicking. +func (v Value) CanInt() bool { + switch v.Kind() { + case Int, Int8, Int16, Int32, Int64: + return true + default: + return false + } +} + func (v Value) Int() int64 { switch v.Kind() { case Int: @@ -287,6 +297,16 @@ func (v Value) Int() int64 { } } +// CanUint reports whether Uint can be used without panicking. +func (v Value) CanUint() bool { + switch v.Kind() { + case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: + return true + default: + return false + } +} + func (v Value) Uint() uint64 { switch v.Kind() { case Uintptr: @@ -330,6 +350,16 @@ func (v Value) Uint() uint64 { } } +// CanFloat reports whether Float can be used without panicking. +func (v Value) CanFloat() bool { + switch v.Kind() { + case Float32, Float64: + return true + default: + return false + } +} + func (v Value) Float32() float32 { switch v.Kind() { case Float32: @@ -377,6 +407,16 @@ func (v Value) Float() float64 { } } +// CanComplex reports whether Complex can be used without panicking. +func (v Value) CanComplex() bool { + switch v.Kind() { + case Complex64, Complex128: + return true + default: + return false + } +} + func (v Value) Complex() complex128 { switch v.Kind() { case Complex64: