Source file src/reflect/type_test.go

     1  // Copyright 2023 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package reflect_test
     6  
     7  import (
     8  	"reflect"
     9  	"testing"
    10  )
    11  
    12  func TestTypeFor(t *testing.T) {
    13  	type (
    14  		mystring string
    15  		myiface  interface{}
    16  	)
    17  
    18  	testcases := []struct {
    19  		wantFrom any
    20  		got      reflect.Type
    21  	}{
    22  		{new(int), reflect.TypeFor[int]()},
    23  		{new(int64), reflect.TypeFor[int64]()},
    24  		{new(string), reflect.TypeFor[string]()},
    25  		{new(mystring), reflect.TypeFor[mystring]()},
    26  		{new(any), reflect.TypeFor[any]()},
    27  		{new(myiface), reflect.TypeFor[myiface]()},
    28  	}
    29  	for _, tc := range testcases {
    30  		want := reflect.ValueOf(tc.wantFrom).Elem().Type()
    31  		if want != tc.got {
    32  			t.Errorf("unexpected reflect.Type: got %v; want %v", tc.got, want)
    33  		}
    34  	}
    35  }
    36  
    37  func TestStructOfEmbeddedIfaceMethodCall(t *testing.T) {
    38  	type Named interface {
    39  		Name() string
    40  	}
    41  
    42  	typ := reflect.StructOf([]reflect.StructField{
    43  		{
    44  			Anonymous: true,
    45  			Name:      "Named",
    46  			Type:      reflect.TypeFor[Named](),
    47  		},
    48  	})
    49  
    50  	v := reflect.New(typ).Elem()
    51  	v.Field(0).Set(
    52  		reflect.ValueOf(reflect.TypeFor[string]()),
    53  	)
    54  
    55  	x := v.Interface().(Named)
    56  	shouldPanic("StructOf does not support methods of embedded interfaces", func() {
    57  		_ = x.Name()
    58  	})
    59  }
    60  

View as plain text