猿问

如何从 []interface{} 转换为 []int?

我想获得非重复的 []int。我正在使用set,但我不知道如何[]int从set. 我怎样才能做到这一点?


package main


import (

    "fmt"

    "math/rand"

    "time"


    "github.com/deckarep/golang-set"

)


func pickup(max int, num int) []int {

    set := mapset.NewSet()


    rand.Seed(time.Now().UnixNano())

    for set.Cardinality() < num {

        n := rand.Intn(max)

        set.Add(n)

    }

    selected := set.ToSlice()

    // Do I need to cast from []interface{} to []int around here?

    // selected.([]int) is error.

    return selected

}


func main() {

    results := pickup(100, 10)

    fmt.Println(results)

    // some processing using []int...

}


长风秋雁
浏览 165回答 1
1回答

函数式编程

没有自动的方法来做到这一点。您需要创建一个 int 切片并将其复制到其中:selected := set.ToSlice()// create a secondary slice of ints, same length as selectedret := make([]int, len(selected))// copy one by onefor i, x := range selected {&nbsp; &nbsp;ret[i] = x.(int) //provided it's indeed int. you can add a check here}return ret
随时随地看视频慕课网APP

相关分类

Go
我要回答