aboutsummaryrefslogtreecommitdiff
path: root/src/reflect/value.go
diff options
context:
space:
mode:
authorIan Lance Taylor <iant@golang.org>2021-07-14 14:46:09 -0700
committerIan Lance Taylor <iant@golang.org>2021-07-21 19:25:48 +0000
commit48c88f1b1bac1ef4fc81246a7f31933f8f922706 (patch)
treefbab30fe4bdc1734cfc86377510be3d50e04e01e /src/reflect/value.go
parent9e26569293c13974d210fd588ebfd29b857d8525 (diff)
downloadgo-48c88f1b1bac1ef4fc81246a7f31933f8f922706.tar.gz
go-48c88f1b1bac1ef4fc81246a7f31933f8f922706.zip
reflect: add Value.CanConvert
For #395 For #46746 Change-Id: I4bfc094cf1cecd27ce48e31f92384cf470f371a6 Reviewed-on: https://go-review.googlesource.com/c/go/+/334669 Trust: Ian Lance Taylor <iant@golang.org> Run-TryBot: Ian Lance Taylor <iant@golang.org> TryBot-Result: Go Bot <gobot@golang.org> Reviewed-by: Keith Randall <khr@golang.org> Reviewed-by: Joe Tsai <thebrokentoaster@gmail.com>
Diffstat (limited to 'src/reflect/value.go')
-rw-r--r--src/reflect/value.go20
1 files changed, 20 insertions, 0 deletions
diff --git a/src/reflect/value.go b/src/reflect/value.go
index 9dce251ac5..6f878eba5b 100644
--- a/src/reflect/value.go
+++ b/src/reflect/value.go
@@ -2811,6 +2811,26 @@ func (v Value) Convert(t Type) Value {
return op(v, t)
}
+// CanConvert reports whether the value v can be converted to type t.
+// If v.CanConvert(t) returns true then v.Convert(t) will not panic.
+func (v Value) CanConvert(t Type) bool {
+ vt := v.Type()
+ if !vt.ConvertibleTo(t) {
+ return false
+ }
+ // Currently the only conversion that is OK in terms of type
+ // but that can panic depending on the value is converting
+ // from slice to pointer-to-array.
+ if vt.Kind() == Slice && t.Kind() == Ptr && t.Elem().Kind() == Array {
+ n := t.Elem().Len()
+ h := (*unsafeheader.Slice)(v.ptr)
+ if n > h.Len {
+ return false
+ }
+ }
+ return true
+}
+
// convertOp returns the function to convert a value of type src
// to a value of type dst. If the conversion is illegal, convertOp returns nil.
func convertOp(dst, src *rtype) func(Value, Type) Value {