Source file test/typeparam/sum.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 (
    10  	"fmt"
    11  )
    12  
    13  func Sum[T interface{ int | float64 }](vec []T) T {
    14  	var sum T
    15  	for _, elt := range vec {
    16  		sum = sum + elt
    17  	}
    18  	return sum
    19  }
    20  
    21  func Abs(f float64) float64 {
    22  	if f < 0.0 {
    23  		return -f
    24  	}
    25  	return f
    26  }
    27  
    28  func main() {
    29  	vec1 := []int{3, 4}
    30  	vec2 := []float64{5.8, 9.6}
    31  	got := Sum[int](vec1)
    32  	want := vec1[0] + vec1[1]
    33  	if got != want {
    34  		panic(fmt.Sprintf("got %d, want %d", got, want))
    35  	}
    36  	got = Sum(vec1)
    37  	if want != got {
    38  		panic(fmt.Sprintf("got %d, want %d", got, want))
    39  	}
    40  
    41  	fwant := vec2[0] + vec2[1]
    42  	fgot := Sum[float64](vec2)
    43  	if Abs(fgot-fwant) > 1e-10 {
    44  		panic(fmt.Sprintf("got %f, want %f", fgot, fwant))
    45  	}
    46  	fgot = Sum(vec2)
    47  	if Abs(fgot-fwant) > 1e-10 {
    48  		panic(fmt.Sprintf("got %f, want %f", fgot, fwant))
    49  	}
    50  }
    51  

View as plain text