go_1.21泛型示例

package demo

import (
    "math/rand"
    "time"
)

// 定义泛型接口
type RandomElementer[T any] interface {
    // 返回一个随机的元素,如果集合为空,返回(zero, false)
    RandomElement() (T, bool)
}

func MustRandom[T any](collection RandomElementer[T]) T {
    val, ok := collection.RandomElement()
    if !ok {
        panic("collection is empty.")
    }
    return val
}

// MyList 泛型集合.
type MyList[T any] []T

// MyList 实现接口RandomElement
func (l MyList[T]) RandomElement() (T, bool) {
    n := len(l)
    if n == 1 {
        return l[0], true
    }

    r := rand.New(rand.NewSource(time.Now().UnixNano()))
    return l[r.Intn(n)], true
}

package demo

import (
    "reflect"
    "testing"
)

func TestMustRandom(t *testing.T) {
    type args struct {
        collection RandomElementer[int]
    }
    tests := []struct {
        name string
        args args
        want int
    }{
        // TODO: Add test cases.
        {
            "case1",
            args{MyList[int]{1, 1, 1}},
            1,
        },
        {
            "case2",
            args{MyList[int]{6, 6, 6}},
            6,
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := MustRandom(tt.args.collection); !reflect.DeepEqual(got, tt.want) {
                t.Errorf("MustRandom() = %v, want %v", got, tt.want)
            }
        })
    }
}

Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.