Source file test/typeparam/mdempsky/13.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  package main
     8  
     9  // Interface which will be used as a regular interface type and as a type bound.
    10  type Mer interface{
    11  	M()
    12  }
    13  
    14  // Interface that is a superset of Mer.
    15  type Mer2 interface {
    16  	M()
    17  	String() string
    18  }
    19  
    20  func F[T Mer](t T) {
    21  	T.M(t)
    22  	t.M()
    23  }
    24  
    25  type MyMer int
    26  
    27  func (MyMer) M() {}
    28  func (MyMer) String() string {
    29  	return "aa"
    30  }
    31  
    32  // Parameterized interface
    33  type Abs[T any] interface {
    34  	Abs() T
    35  }
    36  
    37  func G[T Abs[U], U any](t T) {
    38  	T.Abs(t)
    39  	t.Abs()
    40  }
    41  
    42  type MyInt int
    43  func (m MyInt) Abs() MyInt {
    44  	if m < 0 {
    45  		return -m
    46  	}
    47  	return m
    48  }
    49  
    50  type Abs2 interface {
    51  	Abs() MyInt
    52  }
    53  
    54  
    55  func main() {
    56  	mm := MyMer(3)
    57  	ms := struct{ Mer }{Mer: mm }
    58  
    59  	// Testing F with an interface type arg: Mer and Mer2
    60  	F[Mer](mm)
    61  	F[Mer2](mm)
    62  	F[struct{ Mer }](ms)
    63  	F[*struct{ Mer }](&ms)
    64  
    65  	ms2 := struct { MyMer }{MyMer: mm}
    66  	ms3 := struct { *MyMer }{MyMer: &mm}
    67  
    68  	// Testing F with a concrete type arg
    69  	F[MyMer](mm)
    70  	F[*MyMer](&mm)
    71  	F[struct{ MyMer }](ms2)
    72  	F[struct{ *MyMer }](ms3)
    73  	F[*struct{ MyMer }](&ms2)
    74  	F[*struct{ *MyMer }](&ms3)
    75  
    76  	// Testing G with a concrete type args
    77  	mi := MyInt(-3)
    78  	G[MyInt,MyInt](mi)
    79  
    80  	// Interface Abs[MyInt] holding an mi.
    81  	intMi := Abs[MyInt](mi)
    82  	// First type arg here is Abs[MyInt], an interface type.
    83  	G[Abs[MyInt],MyInt](intMi)
    84  }
    85  

View as plain text