Source file test/interface/fake.go

     1  // run
     2  
     3  // Copyright 2009 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  // Test interface comparisons using types hidden
     8  // inside reflected-on structs.
     9  
    10  package main
    11  
    12  import "reflect"
    13  
    14  type T struct {
    15  	F float32
    16  	G float32
    17  
    18  	S string
    19  	T string
    20  
    21  	U uint32
    22  	V uint32
    23  
    24  	W uint32
    25  	X uint32
    26  
    27  	Y uint32
    28  	Z uint32
    29  }
    30  
    31  func add(s, t string) string {
    32  	return s + t
    33  }
    34  
    35  func assert(b bool) {
    36  	if !b {
    37  		panic("assert")
    38  	}
    39  }
    40  
    41  func main() {
    42  	var x T
    43  	x.F = 1.0
    44  	x.G = x.F
    45  	x.S = add("abc", "def")
    46  	x.T = add("abc", "def")
    47  	x.U = 1
    48  	x.V = 2
    49  	x.W = 1 << 28
    50  	x.X = 2 << 28
    51  	x.Y = 0x12345678
    52  	x.Z = x.Y
    53  
    54  	// check mem and string
    55  	v := reflect.ValueOf(x)
    56  	i := v.Field(0)
    57  	j := v.Field(1)
    58  	assert(i.Interface() == j.Interface())
    59  
    60  	s := v.Field(2)
    61  	t := v.Field(3)
    62  	assert(s.Interface() == t.Interface())
    63  
    64  	// make sure different values are different.
    65  	// make sure whole word is being compared,
    66  	// not just a single byte.
    67  	i = v.Field(4)
    68  	j = v.Field(5)
    69  	assert(i.Interface() != j.Interface())
    70  
    71  	i = v.Field(6)
    72  	j = v.Field(7)
    73  	assert(i.Interface() != j.Interface())
    74  
    75  	i = v.Field(8)
    76  	j = v.Field(9)
    77  	assert(i.Interface() == j.Interface())
    78  }
    79  
    80  /*
    81  comparing uncomparable type float32
    82  throw: interface compare
    83  
    84  panic PC=0x28ceb8 [1]
    85  throw+0x41 /Users/rsc/goX/src/runtime/runtime.c:54
    86  	throw(0x3014a, 0x0)
    87  ifaceeq+0x15c /Users/rsc/goX/src/runtime/iface.c:501
    88  	ifaceeq(0x2aa7c0, 0x0, 0x0, 0x0, 0x2aa7c0, ...)
    89  sys·ifaceeq+0x48 /Users/rsc/goX/src/runtime/iface.c:527
    90  	sys·ifaceeq(0x2aa7c0, 0x0, 0x0, 0x0, 0x2aa7c0, ...)
    91  main·main+0x190 /Users/rsc/goX/src/cmd/gc/x.go:10
    92  	main·main()
    93  mainstart+0xf /Users/rsc/goX/src/runtime/amd64/asm.s:53
    94  	mainstart()
    95  sys·Goexit /Users/rsc/goX/src/runtime/proc.c:124
    96  	sys·Goexit()
    97  */
    98  

View as plain text