| 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 |
func main() { |
| 32 |
PrintWithPrinter( |
| 33 |
"Hello, world.", |
| 34 |
StructWithPrinter{ID: "fake", PrintFn_: Print[string]}, |
| 35 |
) |
| 36 |
} |
| 37 |
|
| 38 |
type StructWithPrinter struct { |
| 39 |
ID string |
| 40 |
PrintFn_ func(string) |
| 41 |
} |
| 42 |
|
| 43 |
// Field accesses through type parameters are disabled |
| 44 |
// until we have a more thorough understanding of the |
| 45 |
// implications on the spec. See issue #51576. |
| 46 |
// Use accessor method instead. |
| 47 |
|
| 48 |
func (s StructWithPrinter) PrintFn() func(string) { |
| 49 |
return s.PrintFn_ |
| 50 |
} |