【go/方法记录】切片乱序

方法

import "math/rand"
func Shuffle(n int, swap func(i, j int))

例子

package main

import (
	"fmt"
	"math/rand"
	"time"
)

type A struct {
	a uint
}

func main() {

	b := make([]*A, 0, 0)

	b = append(b, &A{
		0,
	})
	b = append(b, &A{
		1,
	})
	b = append(b, &A{
		2,
	})

	rand.Seed(time.Now().UnixNano())
	rand.Shuffle(len(b), func(i, j int) { b[i], b[j] = b[j], b[i] })

	fmt.Println(*b[0], *b[1], *b[2])
}
Result:

{2} {1} {0}

{2} {1} {0}

{2} {0} {1}

{0} {1} {2}

你可能感兴趣的:(Go)