duanke0555 2014-12-29 12:38
浏览 1030
已采纳

将[] string转换为[] 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
}

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: 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.

  • 写回答

1条回答 默认 最新

  • duanmei1930 2014-12-29 12:45
    关注

    now I know I'm wrong, []type is a whole type, can't be considered as []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):

    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.

    The FAQ mentions

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

    t := []int{1, 2, 3, 4}
    s := make([]interface{}, len(t))
    for i, v := range t {
        s[i] = v
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败