Source file src/internal/types/testdata/examples/typesets.go
1 // Copyright 2021 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 // This file shows some examples of constraint literals with elided interfaces. 6 // These examples are permitted if proposal issue #48424 is accepted. 7 8 package p 9 10 // Constraint type sets of the form T, ~T, or A|B may omit the interface. 11 type ( 12 _[T int] struct{} 13 _[T ~int] struct{} 14 _[T int | string] struct{} 15 _[T ~int | ~string] struct{} 16 ) 17 18 func min[T int | string](x, y T) T { 19 if x < y { 20 return x 21 } 22 return y 23 } 24 25 func lookup[M ~map[K]V, K comparable, V any](m M, k K) V { 26 return m[k] 27 } 28 29 func deref[P ~*E, E any](p P) E { 30 return *p 31 } 32 33 func _() int { 34 p := new(int) 35 return deref(p) 36 } 37 38 func addrOfCopy[V any, P *V](v V) P { 39 return &v 40 } 41 42 func _() *int { 43 return addrOfCopy(0) 44 } 45 46 // A type parameter may not be embedded in an interface; 47 // so it can also not be used as a constraint. 48 func _[A any, B A /* ERROR "cannot use a type parameter as constraint" */]() {} 49 func _[A any, B, C A /* ERROR "cannot use a type parameter as constraint" */]() {} 50 51 // Error messages refer to the type constraint as it appears in the source. 52 // (No implicit interface should be exposed.) 53 func _[T string](x T) T { 54 return x /* ERROR "constrained by string" */ * x 55 } 56 57 func _[T int | string](x T) T { 58 return x /* ERROR "constrained by int | string" */ * x 59 } 60