| 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 |
type I interface { |
| 10 |
foo() int |
| 11 |
} |
| 12 |
|
| 13 |
// There should be one instantiation of f for both squarer and doubler. |
| 14 |
// Similarly, there should be one instantiation of f for both *incrementer and *decrementer. |
| 15 |
func f[T I](x T) int { |
| 16 |
return x.foo() |
| 17 |
} |
| 18 |
|
| 19 |
type squarer int |
| 20 |
|
| 21 |
func (x squarer) foo() int { |
| 22 |
return int(x*x) |
| 23 |
} |
| 24 |
|
| 25 |
type doubler int |
| 26 |
|
| 27 |
func (x doubler) foo() int { |
| 28 |
return int(2*x) |
| 29 |
} |
| 30 |
|
| 31 |
type incrementer int16 |
| 32 |
|
| 33 |
func (x *incrementer) foo() int { |
| 34 |
return int(*x+1) |
| 35 |
} |
| 36 |
|
| 37 |
type decrementer int32 |
| 38 |
|
| 39 |
func (x *decrementer) foo() int{ |
| 40 |
return int(*x-1) |
| 41 |
} |
| 42 |
|
| 43 |
func main() { |
| 44 |
println(f(squarer(5))) |
| 45 |
println(f(doubler(5))) |
| 46 |
var i incrementer = 5 |
| 47 |
println(f(&i)) |
| 48 |
var d decrementer = 5 |
| 49 |
println(f(&d)) |
| 50 |
} |