Source file test/typeparam/fact.go

     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  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