将 [] 字符串转换为 [] 接口{} [英] Convert []string to []interface{}

查看:24
本文介绍了将 [] 字符串转换为 [] 接口{}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想写一些这样的代码:

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可以互相转换,但其实不是我的本意,可能是还有另一种类型,而不是 []bytestring.

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{}是什么意思?"中提到的.(如果 vinterface{} 变量):

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 of interface{} type.

常见问题提及

它们在内存中的表示不同.

有必要将元素单独复制到目标切片.
此示例将 int 切片转换为 interface{} 切片:

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


Tom L 提议 这个例子(在评论):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆