| 1 |
// -lang=go1.23 -gotypesalias=1 -goexperiment=aliastypeparams |
| 2 |
|
| 3 |
// Copyright 2024 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 |
package aliasTypes |
| 8 |
|
| 9 |
type _ = int |
| 10 |
type _[P any] = int |
| 11 |
|
| 12 |
// A type alias may have fewer type parameters than its RHS. |
| 13 |
type RHS[P any, Q ~int] struct { |
| 14 |
p P |
| 15 |
q Q |
| 16 |
} |
| 17 |
|
| 18 |
type _[P any] = RHS[P, int] |
| 19 |
|
| 20 |
// Or it may have more type parameters than its RHS. |
| 21 |
type _[P any, Q ~int, R comparable] = RHS[P, Q] |
| 22 |
|
| 23 |
// The type parameters of a type alias must implement the |
| 24 |
// corresponding type constraints of the type parameters |
| 25 |
// on the RHS (if any) |
| 26 |
type _[P any, Q ~int] = RHS[P, Q] |
| 27 |
type _[P any, Q int] = RHS[P, Q] |
| 28 |
type _[P int | float64] = RHS[P, int] |
| 29 |
type _[P, Q any] = RHS[P, Q /* ERROR "Q does not satisfy ~int" */] |
| 30 |
|
| 31 |
// A generic type alias may be used like any other generic type. |
| 32 |
type A[P any] = RHS[P, int] |
| 33 |
|
| 34 |
func _(a A[string]) { |
| 35 |
a.p = "foo" |
| 36 |
a.q = 42 |
| 37 |
} |
| 38 |
|
| 39 |
// A generic alias may refer to another generic alias. |
| 40 |
type B[P any] = A[P] |
| 41 |
|
| 42 |
func _(a B[string]) { |
| 43 |
a.p = "foo" |
| 44 |
a.q = 42 |
| 45 |
// error messages print the instantiated alias type |
| 46 |
a.r /* ERROR "a.r undefined (type B[string] has no field or method r)" */ = 0 |
| 47 |
} |