将 []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:我知道[]byte或者string可以相互转换,但这实际上不是我的意图,可能还有另一种类型而不是[]byteand string。


紫衣仙女
浏览 401回答 2
2回答

喵喔喔

创建一个效用函数,像这样func ToGenericArray(arr ...interface{}) []interface{} {    return arr}并使用它:func yourfunc(arr []interface{})  {....}yourfunc(ToGenericArray([...]string{"a", "b", "c"}))重要提示:以下操作无效func yourfunc(arr []interface{})  {....}arr:=[...]string{"a", "b", "c"}yourfunc(ToGenericArray(arr))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go