Source file src/go/doc/testdata/generics.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  // Package generics contains the new syntax supporting generic programming in
     6  // Go.
     7  package generics
     8  
     9  // Variables with an instantiated type should be shown.
    10  var X Type[int]
    11  
    12  // Parameterized types should be shown.
    13  type Type[P any] struct {
    14  	Field P
    15  }
    16  
    17  // Constructors for parameterized types should be shown.
    18  func Constructor[lowerCase any]() Type[lowerCase] {
    19  	return Type[lowerCase]{}
    20  }
    21  
    22  // MethodA uses a different name for its receiver type parameter.
    23  func (t Type[A]) MethodA(p A) {}
    24  
    25  // MethodB has a blank receiver type parameter.
    26  func (t Type[_]) MethodB() {}
    27  
    28  // MethodC has a lower-case receiver type parameter.
    29  func (t Type[c]) MethodC() {}
    30  
    31  // Constraint is a constraint interface with two type parameters.
    32  type Constraint[P, Q interface{ string | ~int | Type[int] }] interface {
    33  	~int | ~byte | Type[string]
    34  	M() P
    35  }
    36  
    37  // int16 shadows the predeclared type int16.
    38  type int16 int
    39  
    40  // NewEmbeddings demonstrates how we filter the new embedded elements.
    41  type NewEmbeddings interface {
    42  	string // should not be filtered
    43  	int16
    44  	struct{ f int }
    45  	~struct{ f int }
    46  	*struct{ f int }
    47  	struct{ f int } | ~struct{ f int }
    48  }
    49  
    50  // Func has an instantiated constraint.
    51  func Func[T Constraint[string, Type[int]]]() {}
    52  
    53  // AnotherFunc has an implicit constraint interface.
    54  //
    55  // Neither type parameters nor regular parameters should be filtered.
    56  func AnotherFunc[T ~struct{ f int }](_ struct{ f int }) {}
    57  
    58  // AFuncType demonstrates filtering of parameters and type parameters. Here we
    59  // don't filter type parameters (to be consistent with function declarations),
    60  // but DO filter the RHS.
    61  type AFuncType[T ~struct{ f int }] func(_ struct{ f int })
    62  
    63  // See issue #49477: type parameters should not be interpreted as named types
    64  // for the purpose of determining whether a function is a factory function.
    65  
    66  // Slice is not a factory function.
    67  func Slice[T any]() []T {
    68  	return nil
    69  }
    70  
    71  // Single is not a factory function.
    72  func Single[T any]() *T {
    73  	return nil
    74  }
    75  

View as plain text