我想获得非重复的 []int。我正在使用set,但我不知道如何[]int从set. 我怎样才能做到这一点?package mainimport ( "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 回答
函数式编程
TA贡献1807条经验 获得超9个赞
没有自动的方法来做到这一点。您需要创建一个 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
- 1 回答
- 0 关注
- 164 浏览
添加回答
举报
0/150
提交
取消