How to convert interface{} to []int?

huangapple go评论66阅读模式
英文:

How to convert interface{} to []int?

问题

我正在使用Go编程语言进行编程。

假设有一个类型为interface{}的变量,其中包含一个整数数组。我该如何将interface{}转换回[]int类型?

我尝试了以下方法:

interface_variable.([]int)

但是我得到了以下错误:

panic: interface conversion: interface is []interface {}, not []int
英文:

I am programming in Go programming language.

Say there's a variable of type interface{} that contains an array of integers. How do I convert interface{} back to []int?

I have tried

interface_variable.([]int)

The error I got is:

panic: interface conversion: interface is []interface {}, not []int

答案1

得分: 15

这是一个[]interface{}而不仅仅是一个interface{},你需要遍历它并进行转换:

2022年的解答

https://go.dev/play/p/yeihkfIZ90U

func ConvertSlice[E any](in []any) (out []E) {
	out = make([]E, 0, len(in))
	for _, v := range in {
		out = append(out, v.(E))
	}
	return
}

go1.18之前的解答

http://play.golang.org/p/R441h4fVMw

func main() {
	a := []interface{}{1, 2, 3, 4, 5}
	b := make([]int, len(a))
	for i := range a {
		b[i] = a[i].(int)
	}
	fmt.Println(a, b)
}
英文:

It's a []interface{} not just one interface{}, you have to loop through it and convert it:

the 2022 answer

https://go.dev/play/p/yeihkfIZ90U

func ConvertSlice[E any](in []any) (out []E) {
	out = make([]E, 0, len(in))
	for _, v := range in {
		out = append(out, v.(E))
	}
	return
}

the pre-go1.18 answer

http://play.golang.org/p/R441h4fVMw

func main() {
	a := []interface{}{1, 2, 3, 4, 5}
	b := make([]int, len(a))
	for i := range a {
		b[i] = a[i].(int)
	}
	fmt.Println(a, b)
}

答案2

得分: 2

正如其他人所说,你应该迭代切片并逐个转换对象。
最好在范围内使用类型开关以避免发生恐慌:

a := []interface{}{1, 2, 3, 4, 5}
b := make([]int, len(a))
for i, value := range a {
switch typedValue := value.(type) {
case int:
b[i] = typedValue
break
default:
fmt.Println("不是int类型:", value)
}
}
fmt.Println(a, b)

http://play.golang.org/p/Kbs3rbu2Rw

英文:

As others have said, you should iterate the slice and convert the objects one by one.
Is better to use a type switch inside the range in order to avoid panics:

a := []interface{}{1, 2, 3, 4, 5}
b := make([]int, len(a))
for i, value := range a {
	switch typedValue := value.(type) {
	case int:
		b[i] = typedValue
		break
	default:
		fmt.Println("Not an int: ", value)
	}
}
fmt.Println(a, b)

http://play.golang.org/p/Kbs3rbu2Rw

答案3

得分: 0

以下是翻译好的内容:

函数的返回值类型是interface{},但实际返回的值是[]interface{},所以请尝试使用以下代码:

func main() {
    values := returnValue.([]interface{})
    for i := range values {
        fmt.Println(values[i])
    }
}
英文:

Func return value is interface{} but real return value is []interface{}, so try this instead:

func main() {
    values := returnValue.([]interface{})
    for i := range values {
	    fmt.Println(values[i])
    }
}

huangapple
  • 本文由 发表于 2014年6月27日 21:46:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/24453420.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定