将 [] 字符串转换为 [] 接口{} [英] Convert []string to []interface{}
问题描述
我只想写一些这样的代码:
I just want to write some code like this:
func (w Writer) WriteVString(strs []string) (int, error) {
return writeV(func(index int, str interface{}) (int, error) {
return w.WriteString(str.(string))
}, strs) // it doesn't work
}
func (w Writer) WriteV(bs [][]byte) (int, error) {
return writeV(func(index int, b interface{}) (int, error) {
return w.Write(b.([]byte))
}, []interface{}{bs...}) // it also can't be compiled
}
type writeFunc func(int, interface{}) (int, error)
func writeV(fn writeFunc, slice []interface{}) (n int, err error) {
var m int
for index, s := range slice {
if m, err = fn(index, s); err != nil {
break
}
n += m
)
return
}
我以为interface{}
可以代表任何类型,所以[]interface
也可以代表任何[]type
,现在我知道了我错了,[]type
是一个整体类型,不能认为是[]interface{}
.
I thought interface{}
can represent any type, so []interface
can also represent any []type
before, now I know I'm wrong, []type
is a whole type, can't be considered as []interface{}
.
那么,任何人都可以帮助我如何使这段代码工作,或任何其他解决方案?
So, can anyone help me how to make this code work, or any other solution?
PS:我知道[]byte
或者string
可以互相转换,但其实不是我的本意,可能是还有另一种类型,而不是 []byte
和 string
.
PS: I know that []byte
or string
can be converted to one another, but it's not actually my intention, may be there is another type rather than []byte
and string
.
推荐答案
现在我知道我错了,
[]type
是一个完整的类型,不能认为是[]interface{}
.
now I know I'm wrong,
[]type
is a whole type, can't be considered as[]interface{}
.
是的,这是因为 interface{}
是它自己的类型(而不是任何其他类型的别名").
正如我在golang中的interface{}
是什么意思?"中提到的.(如果 v
是 interface{}
变量):
Yes, and that is because interface{}
is its own type (and not an "alias" for any other type).
As I mention in "what is the meaning of interface{}
in golang?" (if v
is a interface{}
variable):
新手地鼠被引导相信v
是任何类型",但这是错误的.v
不是任何类型;它是 interface{}
类型的.
Beginner gophers are led to believe that "
v
is of any type", but that is wrong.
v
is not of any type; it is ofinterface{}
type.
它们在内存中的表示不同.
有必要将元素单独复制到目标切片.
此示例将 int 切片转换为 interface{}
切片:
t := []int{1, 2, 3, 4}
s := make([]interface{}, len(t))
for i, v := range t {
s[i] = v
}
package main
import "fmt"
func main() {
x := []string{"a", "b", "c", "d"}
fmt.Printf("%T: %v
", x, x)
//converting a []string to a []interface{}
y := make([]interface{}, len(x))
for i, v := range x {
y[i] = v
}
fmt.Printf("%T: %v
", y, y)
//converting a []interface{} to a []string
z := make([]string, len(y))
for i, v := range y {
z[i] = fmt.Sprint(v)
}
fmt.Printf("%T: %v
", z, z)
}
这篇关于将 [] 字符串转换为 [] 接口{}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!