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

时间:2015-12-24 16:18:38

标签: go

我想得到非重复的[] 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...
}

1 个答案:

答案 0 :(得分:2)

没有自动的方法可以做到这一点。您需要创建一个int切片并将其复制到其中:

selected := set.ToSlice()

// create a secondary slice of ints, same length as selected
ret := make([]int, len(selected))

// copy one by one
for i, x := range selected {
   ret[i] = x.(int) //provided it's indeed int. you can add a check here
}

return ret