Source file test/typeparam/issue50690b.go

     1  // run
     2  
     3  // Copyright 2022 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  import (
    10  	"fmt"
    11  )
    12  
    13  type Printer[T ~string] struct {
    14  	PrintFn func(T)
    15  }
    16  
    17  func Print[T ~string](s T) {
    18  	fmt.Println(s)
    19  }
    20  
    21  func PrintWithPrinter[T ~string, S interface {
    22  	~struct {
    23  		ID       T
    24  		PrintFn_ func(T)
    25  	}
    26  	PrintFn() func(T)
    27  }](message T, obj S) {
    28  	obj.PrintFn()(message)
    29  }
    30  
    31  type PrintShop[T ~string] struct {
    32  	ID       T
    33  	PrintFn_ func(T)
    34  }
    35  
    36  // Field accesses through type parameters are disabled
    37  // until we have a more thorough understanding of the
    38  // implications on the spec. See issue #51576.
    39  // Use accessor method instead.
    40  
    41  func (s PrintShop[T]) PrintFn() func(T) { return s.PrintFn_ }
    42  
    43  func main() {
    44  	PrintWithPrinter(
    45  		"Hello, world.",
    46  		PrintShop[string]{
    47  			ID:       "fake",
    48  			PrintFn_: Print[string],
    49  		},
    50  	)
    51  }
    52  

View as plain text