Skip to content

reflect: TypeAssert[T] is not identical to Interface().(T) #74404

Closed
@dsnet

Description

@dsnet

Go version

go1.25rc1

Output of go env in your module/workspace:

n/a

What did you do?

Run the following program:

var v error
rv := reflect.ValueOf(&v).Elem()
v1, ok1 := rv.Interface().(error)
fmt.Println(v1, ok1)
v2, ok2 := reflect.TypeAssert[error](rv)
fmt.Println(v2, ok2)

What did you see happen?

This prints:

<nil> false
<nil> true

What did you expect to see?

As currently documented, TypeAssert[T](v) is semantically identical to v.Interface().(T).

If so, this should print:

<nil> false
<nil> false

We should either:

  1. Fix the implementation of TypeAssert to match the documented behavior.
  2. Fix the documentation of TypeAssert that it handles nil interface values.

I don't feel strongly what we should do. The advantage of option1 is that the documented semantics is simple, but the advantage of 2 is that it more correctly matches what is going on under-the-hood. An argument for option 2 is that TypeFor is not the same as TypeOf when it comes to interface values. Thus, one could argue that divergence in behavior just for interfaces is reasonable. In this particular case, the divergence is limited to just nil interface values, which is an even smaller divergence.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugReportIssues describing a possible bug in the Go implementation.NeedsFixThe path to resolution is known, but the work has not been done.release-blocker

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions