将[] string转换为[] interface {}

余弦

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

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{}

因此,有人可以帮助我如何使此代码正常工作,或提供其他解决方案吗?

PS:我知道[]bytestring可以互相转换,但是实际上这并不是我的意图,可能还有另一种类型,而不是[]byteand string

VonC:

现在我知道我错了,[]type是一个整体类型,不能视为[]interface{}

是的,那是因为interface{}它是它自己的类型(而不是其他任何类型的“别名”)。
正如我在“ golang中的含义是interface{}什么? ”(如果vinterface{}变量)中提到的那样

导致地鼠的人相信“ v任何类型”,但这是错误的。
v不是任何类型;它是interface{}类型的。

常见问题中提到

它们在内存中没有相同的表示

有必要将元素分别复制到目标切片
本示例将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\n", 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\n", 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\n", z, z)

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将map [interface {}] interface {}转换为map [string] string

将interface {}转换为[] interface {}

将interface {}转换为int

将结构转换为* interface {}

如何将 map[string]interface{} 转换为 map[string]string

将Class <Object>转换为Class <Interface>

如何将 []interface 转换为 []struct

如何将interface {}转换为[] int?

将interface {}转换为特定类型

如何将map [string] interface {}中的不同值转换为string类型

前往:将JSON字符串转换为map [string] interface {}

我如何将BSON文档转换为map [string] interface {}

外部类型问题的JSON序列化-将map [string] interface {}项转换为int

如何将多维切片[] interface {}转换为切片[] string?

将mgo与转换为map [string] interface {}的嵌套文档一起使用。如何遍历地图?

是否可以将 map[string]string 转换为 map[string]interface{} 而无需在 golang 中使用 for 循环?

无法将[] interface {}转换为[] byte:“ interface {}是[] interface [],而不是[] uint8”

将interface {}转换为字符串数组

如何将interface {}转换为字符串?

无法将活动强制转换为Interface(ClassCastException)

无法将类型'Task <Derived>'转换为'Task <Interface>'

如何将interface {}转换为bytes.Buffer

将[] interface {}转换为非可变函数的参数

将Interface Builder设置转换为Objective-C

如何将interface {}转换为结构指针?

无法将Lazy <Class>隐式转换为Lazy <Interface>

将WPA_passphrase输出转换为/ etc / network / interface

将NSData转换为String?

将String转换为unicode?