go泛型小记

======

package main

import "fmt"

// Number declare a type constraint
type Number interface {
    int64 | float64 | int32 | int
}

type ListNode[T Number] struct {
    value T
    next  *ListNode[T]
}

// SumInts 非泛型求和函数,int64类型
func SumInts(m map[string]int64) int64 {
    var s int64
    for _, v := range m {
        s += v
    }
    return s
}

// SumFloats 非泛型求和函数 float64类型
func SumFloats(m map[string]float64) float64 {
    var s float64
    for _, v := range m {
        s += v
    }
    return s
}

// SumIntsOrFloats sums the values of map m. It supports both int64 and float64
// as types for map values.
// K 和 V 是类型参数
func SumIntsOrFloats[K comparable, V int64 | float64](m map[K]V) V {
    var s V
    for _, v := range m {
        s += v
    }
    return s
}

func SumNumbers[K comparable, V Number](m map[K]V) V {
    var s V
    for _, v := range m {
        s += v
    }
    return s
}

func main() {
    // Initialize a map for the integer values
    ints := map[string]int64{
        "first":  34,
        "second": 12,
    }

    // Initialize a map for the float values
    floats := map[string]float64{
        "first":  35.98,
        "second": 26.99,
    }

    fmt.Printf("Non-Generic Sums: %v and %v\n", SumInts(ints), SumFloats(floats))

    // 泛型函数如何调用
    fmt.Printf("Generic Sums: %v and %v\n",
        SumIntsOrFloats(ints),
        SumIntsOrFloats(floats))

    fmt.Printf("Generic Sums with Constranint: %v and %v\n", SumNumbers(ints), SumNumbers(floats))

    //
    oneNode := ListNode[int64]{value: 34, next: nil}
    fmt.Printf("oneNode = %+v\n", oneNode)
}

Leave a Comment

Your email address will not be published. Required fields are marked *

PHP 8.1.1 - 18.618 ms, 0 Q