Skip to content

Commit

Permalink
reflect: add TypeFor
Browse files Browse the repository at this point in the history
Fixes #60088

Change-Id: I7b43d329def22c2524501ba1d6bfc73becc823d1
GitHub-Last-Rev: becd714c4562da4a3280c3a56ebaf246e48e9f37
GitHub-Pull-Request: golang/go#61598
Reviewed-on: https://go-review.googlesource.com/c/go/+/513478
TryBot-Result: Gopher Robot <[email protected]>
Run-TryBot: Ian Lance Taylor <[email protected]>
Auto-Submit: Ian Lance Taylor <[email protected]>
Reviewed-by: David Chase <[email protected]>
Reviewed-by: Ian Lance Taylor <[email protected]>
Run-TryBot: Ian Lance Taylor <[email protected]>
  • Loading branch information
earthboundkid authored and gopherbot committed Jul 31, 2023
1 parent f024e39 commit 42d2dfb
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions api/next/60088.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pkg reflect, func TypeFor[$0 interface{}]() Type #60088
5 changes: 5 additions & 0 deletions src/reflect/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -2911,3 +2911,8 @@ func addTypeBits(bv *bitVector, offset uintptr, t *abi.Type) {
}
}
}

// TypeFor returns the [Type] that represents the type argument T.
func TypeFor[T any]() Type {
return TypeOf((*T)(nil)).Elem()
}
35 changes: 35 additions & 0 deletions src/reflect/type_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package reflect_test

import (
"reflect"
"testing"
)

func TestTypeFor(t *testing.T) {
type (
mystring string
myiface interface{}
)

testcases := []struct {
wantFrom any
got reflect.Type
}{
{new(int), reflect.TypeFor[int]()},
{new(int64), reflect.TypeFor[int64]()},
{new(string), reflect.TypeFor[string]()},
{new(mystring), reflect.TypeFor[mystring]()},
{new(any), reflect.TypeFor[any]()},
{new(myiface), reflect.TypeFor[myiface]()},
}
for _, tc := range testcases {
want := reflect.ValueOf(tc.wantFrom).Elem().Type()
if want != tc.got {
t.Errorf("unexpected reflect.Type: got %v; want %v", tc.got, want)
}
}
}

0 comments on commit 42d2dfb

Please sign in to comment.