Golang GENERICS TYPE simple example. Golang quick tips #shorts



Golang GENERICS TYPE simple example. Golang quick tips #shorts

Golang GENERICS TYPE simple example. Golang quick tips #shorts

Go Programming Language simple example of generics type.
Return integer when we pass a slice of integers.
Return float64 when we pass a slice of float64.
This is a quick golang tips for beginner.
#devlog
Source code on github: https://github.com/sokhuong-uon/go-shorts/blob/generics/simple-generics/main.go

Or quickly grab the code:

package main
import “fmt”

func sum[T int | float64](slice []T) T {
var sum T
sum = 0

for _, v := range slice {
sum += v
}

return sum
}

func main() {
intSlice := []int{3, 6, 1, 8}
floatSlice := []float64{3.3, 6.1, 8.5}

intSum := sum(intSlice)
floatSum := sum(floatSlice)

fmt.Println(intSum)
fmt.Println(floatSum)
}