Numeric Sum With Generic Constraints

Sum int and float slices through one generic function whose constraint unions numeric types, keeping a single call site per element type.

GoData Integrity

Code

gosnippet
27 lines
package main

import "fmt"

// 约束并集:int/int64/float64 都满足,编译期即可校验
type Number interface {
	~int | ~int64 | ~float64
}

func Sum[T Number](values []T) T {
	var total T
	for _, v := range values {
		total += v
	}
	return total
}

func main() {
	coins := []int{5, 10, 25}
	prices := []float64{1.25, 2.5, 0.75}

	fmt.Println("coins sum:", Sum(coins))
	fmt.Printf("prices sum: %.2f\n", Sum(prices))

	// 泛型让同一算法服务多个元素类型,调用点仍是具体类型
	fmt.Printf("types: %T / %T\n", Sum(coins), Sum(prices))
}

Following the run order

Numeric Sum With Generic Constraints comes down to the function main.

A single loop drives the file — for _, v := range values.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Using it

Signature: func main()

Running the file prints labeled results such as coins sum:, prices sum:, types: — each operation’s effect is visible in the output.

Key statements

func Sum[T Number](values []T) T {
var total T
for _, v := range values {
total += v
}
return total
}
func main() {
coins := []int{5, 10, 25}
prices := []float64{1.25, 2.5, 0.75}
fmt.Println("coins sum:", Sum(coins))
fmt.Printf("prices sum: %.2f\n", Sum(prices))
// 泛型让同一算法服务多个元素类型,调用点仍是具体类型
fmt.Printf("types: %T / %T\n", Sum(coins), Sum(prices))
}

Interactive Tools for This Topic

FAQ

What does Numeric Sum With Generic Constraints print when run?
No setup needed: run the file and look for labeled lines like `coins sum:`, `prices sum:`, `types:` in the output.