2021-02-03 16:45:26 -07:00
|
|
|
// run -gcflags=-G=3
|
|
|
|
|
|
|
|
// Copyright 2021 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
2021-02-08 11:23:05 -07:00
|
|
|
func sum[T interface{ type int, float64 }](vec []T) T {
|
2021-02-03 16:45:26 -07:00
|
|
|
var sum T
|
|
|
|
for _, elt := range vec {
|
|
|
|
sum = sum + elt
|
|
|
|
}
|
|
|
|
return sum
|
|
|
|
}
|
|
|
|
|
|
|
|
func abs(f float64) float64 {
|
|
|
|
if f < 0.0 {
|
|
|
|
return -f
|
|
|
|
}
|
|
|
|
return f
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
vec1 := []int{3, 4}
|
|
|
|
vec2 := []float64{5.8, 9.6}
|
2021-02-08 11:23:05 -07:00
|
|
|
got := sum[int](vec1)
|
2021-02-03 16:45:26 -07:00
|
|
|
want := vec1[0] + vec1[1]
|
2021-02-08 11:23:05 -07:00
|
|
|
if got != want {
|
|
|
|
panic(fmt.Sprintf("Got %d, want %d", got, want))
|
2021-02-03 16:45:26 -07:00
|
|
|
}
|
2021-02-08 11:23:05 -07:00
|
|
|
got = sum(vec1)
|
2021-02-03 16:45:26 -07:00
|
|
|
if want != got {
|
2021-02-08 11:23:05 -07:00
|
|
|
panic(fmt.Sprintf("Got %d, want %d", got, want))
|
2021-02-03 16:45:26 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
fwant := vec2[0] + vec2[1]
|
2021-02-08 11:23:05 -07:00
|
|
|
fgot := sum[float64](vec2)
|
2021-02-03 16:45:26 -07:00
|
|
|
if abs(fgot - fwant) > 1e-10 {
|
2021-02-08 11:23:05 -07:00
|
|
|
panic(fmt.Sprintf("Got %f, want %f", fgot, fwant))
|
2021-02-03 16:45:26 -07:00
|
|
|
}
|
2021-02-08 11:23:05 -07:00
|
|
|
fgot = sum(vec2)
|
2021-02-03 16:45:26 -07:00
|
|
|
if abs(fgot - fwant) > 1e-10 {
|
2021-02-08 11:23:05 -07:00
|
|
|
panic(fmt.Sprintf("Got %f, want %f", fgot, fwant))
|
2021-02-03 16:45:26 -07:00
|
|
|
}
|
|
|
|
}
|