Source file test/genmeth.go

     1  // skip
     2  
     3  // Copyright 2026 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  // Verify that generic methods are assembled correctly.
     8  
     9  package main
    10  
    11  import "fmt"
    12  
    13  type List[E any] []E
    14  
    15  func (l List[E]) apply[P any](f func(E) P) List[P] {
    16  	r := make(List[P], len(l))
    17  	for i, x := range l {
    18  		r[i] = f(x)
    19  	}
    20  	return r
    21  }
    22  
    23  func (l List[E]) print() string {
    24  	s := ""
    25  	for i, x := range l {
    26  		if i > 0 {
    27  			s += "->"
    28  		}
    29  		s += fmt.Sprint(x)
    30  	}
    31  	return s
    32  }
    33  
    34  func main() {
    35  	l := make(List[int], 3)
    36  	for i := range l {
    37  		l[i] = i
    38  	}
    39  
    40  	f := func(i int) string {
    41  		return string("abc"[i])
    42  	}
    43  
    44  	if r := l.apply(f).print(); r != "a->b->c" {
    45  		panic(fmt.Sprintf("got %s, want a->b->c", r))
    46  	}
    47  }
    48  

View as plain text