github.com/traefik/yaegi@v0.15.1/_test/assert1.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  	"time"
     7  )
     8  
     9  type TestStruct struct{}
    10  
    11  func (t TestStruct) String() string {
    12  	return "hello world"
    13  }
    14  
    15  type DummyStringer interface{
    16  	String() string
    17  }
    18  
    19  func main() {
    20  	aType := reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
    21  
    22  	var t interface{}
    23  	t = time.Nanosecond
    24  	s, ok := t.(fmt.Stringer)
    25  	if !ok {
    26  		fmt.Println("time.Nanosecond does not implement fmt.Stringer")
    27  		return
    28  	}
    29  	fmt.Println(s.String())
    30  	fmt.Println(t.(fmt.Stringer).String())
    31  	bType := reflect.TypeOf(time.Nanosecond)
    32  	fmt.Println(bType.Implements(aType))
    33  
    34  	// not redundant with the above, because it goes through a slightly different code path.
    35  	if _, ok := t.(fmt.Stringer); !ok {
    36  		fmt.Println("time.Nanosecond does not implement fmt.Stringer")
    37  		return
    38  	} else {
    39  		fmt.Println("time.Nanosecond implements fmt.Stringer")
    40  	}
    41  
    42  	t = 42
    43  	foo, ok := t.(fmt.Stringer)
    44  	if !ok {
    45  		fmt.Println("42 does not implement fmt.Stringer")
    46  	} else {
    47  		fmt.Println("42 implements fmt.Stringer")
    48  		return
    49  	}
    50  	_ = foo
    51  
    52  	if _, ok := t.(fmt.Stringer); !ok {
    53  		fmt.Println("42 does not implement fmt.Stringer")
    54  	} else {
    55  		fmt.Println("42 implements fmt.Stringer")
    56  		return
    57  	}
    58  
    59  	// TODO(mpl): restore when fixed
    60  	// var tt interface{}
    61  	var tt DummyStringer
    62  	tt = TestStruct{}
    63  	ss, ok := tt.(fmt.Stringer)
    64  	if !ok {
    65  		fmt.Println("TestStuct does not implement fmt.Stringer")
    66  		return
    67  	}
    68  	fmt.Println(ss.String())
    69  	fmt.Println(tt.(fmt.Stringer).String())
    70  
    71  	if _, ok := tt.(fmt.Stringer); !ok {
    72  		fmt.Println("TestStuct does not implement fmt.Stringer")
    73  		return
    74  	} else {
    75  		fmt.Println("TestStuct implements fmt.Stringer")
    76  	}
    77  }
    78  
    79  // Output:
    80  // 1ns
    81  // 1ns
    82  // true
    83  // time.Nanosecond implements fmt.Stringer
    84  // 42 does not implement fmt.Stringer
    85  // 42 does not implement fmt.Stringer
    86  // hello world
    87  // hello world
    88  // TestStuct implements fmt.Stringer