关于go:如何从[] interface {}转换为[] int?


How can I cast from []interface{} to []int?

本问题已经有最佳答案,请猛点这里访问。

我想得到不重复的。我用的是set,但我不知道如何从set得到[]int。我该怎么做?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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...
}


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

1
2
3
4
5
6
7
8
9
10
11
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