goalng类型转换 []T 转 []interface{}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
"fmt"
"strconv"
)

var i int = 10

func () {

str1 := strconv.Itoa(i)

// 通过Sprintf方法转换
str2 := fmt.Sprintf("%d", i)

// 打印str1
fmt.Println(str1)
// 打印str2
fmt.Println(str2)
}

[]T 转 []interface{}

Can I convert a []T to an []interface{}?
Not directly, because they do not have the same representation in memory. It is necessary to copy the elements individually to the destination slice. This example converts a slice of int to a slice of interface{}:

1
2
3
4
5
t := []int{1, 2, 3, 4}
s := make([]interface{}, len(t))
for i, v := range t {
s[i] = v
}