github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/test/cmp6.go (about) 1 // errorcheck 2 3 // Copyright 2010 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 // Verify that incorrect comparisons are detected. 8 // Does not compile. 9 10 package main 11 12 func use(bool) {} 13 14 type T1 *int 15 type T2 *int 16 17 type T3 struct{ z []int } 18 19 var t3 T3 20 21 type T4 struct { _ []int; a float64 } 22 23 var t4 T4 24 25 func main() { 26 // Arguments to comparison must be 27 // assignable one to the other (or vice versa) 28 // so chan int can be compared against 29 // directional channels but channel of different 30 // direction cannot be compared against each other. 31 var c1 chan<- int 32 var c2 <-chan int 33 var c3 chan int 34 35 use(c1 == c2) // ERROR "invalid operation|incompatible" 36 use(c2 == c1) // ERROR "invalid operation|incompatible" 37 use(c1 == c3) 38 use(c2 == c2) 39 use(c3 == c1) 40 use(c3 == c2) 41 42 // Same applies to named types. 43 var p1 T1 44 var p2 T2 45 var p3 *int 46 47 use(p1 == p2) // ERROR "invalid operation|incompatible" 48 use(p2 == p1) // ERROR "invalid operation|incompatible" 49 use(p1 == p3) 50 use(p2 == p2) 51 use(p3 == p1) 52 use(p3 == p2) 53 54 // Comparison of structs should have a good message 55 use(t3 == t3) // ERROR "struct|expected" 56 use(t4 == t4) // ok; the []int is a blank field 57 58 // Slices, functions, and maps too. 59 var x []int 60 var f func() 61 var m map[int]int 62 use(x == x) // ERROR "slice can only be compared to nil" 63 use(f == f) // ERROR "func can only be compared to nil" 64 use(m == m) // ERROR "map can only be compared to nil" 65 66 // Comparison with interface that cannot return true 67 // (would panic). 68 var i interface{} 69 use(i == x) // ERROR "invalid operation" 70 use(x == i) // ERROR "invalid operation" 71 use(i == f) // ERROR "invalid operation" 72 use(f == i) // ERROR "invalid operation" 73 use(i == m) // ERROR "invalid operation" 74 use(m == i) // ERROR "invalid operation" 75 }