blob: cf01072d8cb06003ea8a8e7a0a5a19fd86c716ff [file] [log] [blame]
Dan Willemsenbc60c3c2021-12-15 01:09:00 -08001// 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
8package p
9
10// Constraint type sets of the form T, ~T, or A|B may omit the interface.
11type (
12 _[T int] struct{}
13 _[T ~int] struct{}
14 _[T int|string] struct{}
15 _[T ~int|~string] struct{}
16)
17
18func min[T int|string](x, y T) T {
19 if x < y {
20 return x
21 }
22 return y
23}
24
25func lookup[M ~map[K]V, K comparable, V any](m M, k K) V {
26 return m[k]
27}
28
29func deref[P ~*E, E any](p P) E {
30 return *p
31}
32
33func _() int {
34 p := new(int)
35 return deref(p)
36}
37
38func addrOfCopy[V any, P ~*V](v V) P {
39 return &v
40}
41
42func _() *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.
48func _[A any, B A /* ERROR cannot use a type parameter as constraint */ ]() {}
49
50// Error messages refer to the type constraint as it appears in the source.
51// (No implicit interface should be exposed.)
52func _[T string](x T) T {
53 return x /* ERROR constrained by string */ * x
54}
55
56func _[T int|string](x T) T {
57 return x /* ERROR constrained by int|string */ * x
58}