Source file test/typeparam/equal.go

     1  // run
     2  
     3  // Copyright 2021 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  // comparisons of type parameters to interfaces
     8  
     9  package main
    10  
    11  func f[T comparable](t, u T) bool {
    12  	// Comparing two type parameters directly.
    13  	// (Not really testing comparisons to interfaces, but just 'cause we're here.)
    14  	return t == u
    15  }
    16  
    17  func g[T comparable](t T, i interface{}) bool {
    18  	// Compare type parameter value to empty interface.
    19  	return t == i
    20  }
    21  
    22  type I interface {
    23  	foo()
    24  }
    25  
    26  type C interface {
    27  	comparable
    28  	I
    29  }
    30  
    31  func h[T C](t T, i I) bool {
    32  	// Compare type parameter value to nonempty interface.
    33  	return t == i
    34  }
    35  
    36  type myint int
    37  
    38  func (x myint) foo() {
    39  }
    40  
    41  func k[T comparable](t T, i interface{}) bool {
    42  	// Compare derived type value to interface.
    43  	return struct{ a, b T }{t, t} == i
    44  }
    45  
    46  func main() {
    47  	assert(f(3, 3))
    48  	assert(!f(3, 5))
    49  	assert(g(3, 3))
    50  	assert(!g(3, 5))
    51  	assert(h(myint(3), myint(3)))
    52  	assert(!h(myint(3), myint(5)))
    53  
    54  	type S struct{ a, b float64 }
    55  
    56  	assert(f(S{3, 5}, S{3, 5}))
    57  	assert(!f(S{3, 5}, S{4, 6}))
    58  	assert(g(S{3, 5}, S{3, 5}))
    59  	assert(!g(S{3, 5}, S{4, 6}))
    60  
    61  	assert(k(3, struct{ a, b int }{3, 3}))
    62  	assert(!k(3, struct{ a, b int }{3, 4}))
    63  }
    64  
    65  func assert(b bool) {
    66  	if !b {
    67  		panic("assertion failed")
    68  	}
    69  }
    70  

View as plain text