1
2
3
4
5
6
7 package main
8
9 import "fmt"
10
11 func fact[T interface{ ~int | ~int64 | ~float64 }](n T) T {
12 if n == 1 {
13 return 1
14 }
15 return n * fact(n-1)
16 }
17
18 func main() {
19 const want = 120
20
21 if got := fact(5); got != want {
22 panic(fmt.Sprintf("got %d, want %d", got, want))
23 }
24
25 if got := fact[int64](5); got != want {
26 panic(fmt.Sprintf("got %d, want %d", got, want))
27 }
28
29 if got := fact(5.0); got != want {
30 panic(fmt.Sprintf("got %f, want %f", got, want))
31 }
32 }
33
View as plain text