reflect: document corner cases of TypeAssert

These cases might not be obvious just by looking at the
generic function signature and might be worth explicitly
mentioning in the doc comment.

Updates #78007
Updates #62121

Change-Id: Ic0b0f78f4f87d35d0463c09ed5476c336a6a6964
Reviewed-on: https://go-review.googlesource.com/c/go/+/753741
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Joseph Tsai <joetsai@digital-static.net>
Reviewed-by: Mark Freeman <markfreeman@google.com>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Auto-Submit: Mateusz Poliwczak <mpoliwczak34@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
This commit is contained in:
Mateusz Poliwczak
2026-03-10 18:45:01 +01:00
committed by Gopher Robot
parent dbb3793b59
commit 4135faca66

View File

@@ -1515,6 +1515,17 @@ func valueInterface(v Value, safe bool) any {
// TypeAssert is semantically equivalent to:
//
// v2, ok := v.Interface().(T)
//
// Note that this function, just as the type assertion above, might return:
//
// - ok == false when v.Type() == reflect.TypeFor[T]()
// For example, when both T and v are interface types and v.IsNil() == true.
// In that case v.Interface() returns a nil interface value, and the
// assertion .(T) fails with ok == false.
//
// - ok == true when v.Type() != reflect.TypeFor[T]().
// For example, when T is an interface type and v holds a value whose
// concrete type implements T.
func TypeAssert[T any](v Value) (T, bool) {
if v.flag == 0 {
panic(&ValueError{"reflect.TypeAssert", Invalid})