doujia9833 2018-10-30 07:52
浏览 150
已采纳

append()中的“…”符号不适用于追加不同类型的切片

I need an abstracted slice that contains multiple types. The most simplified code is this:

package main

import "fmt"

type A interface{}

type X string

func main() {
    sliceA := make([]A, 0, 0)
    sliceX := []X{"x1", "x2"}
    var appendedSlice []A
    appendedSlice = append(sliceA, sliceX[0], sliceX[1])  // (1) works
    appendedSlice = append(sliceA, sliceX...)             // (2) doesn't work
    fmt.Println(appendedSlice)

}

In my real program, the interface A defines some functions, and X and also other types implement it.

Line (2) raises an error cannot use sliceX (type []X) as type []A in append.

I thought (2) is a syntax sugar for (1), but I'm probably missing something... Do I have to always add an element X into slice A one by one?

Thank you guys in advance!

  • 写回答

1条回答 默认 最新

  • douqie3391 2018-10-30 08:05
    关注

    The problem is that interface{} and string are two different types. To convert a slice from string to interface{} you will have to do it in one of the following ways:

    create sliceA and initialize its size to sliceX length

    sliceA := make([]A, len(sliceX))
    for ix, item := range sliceX {
        sliceA[ix] = item
    }
    

    dynamically append sliceX items to appendedSlice

    var appendedSlice []A
    for ix := range sliceX {
        appendedSlice = append(appendedSlice, sliceX[ix])
    }
    

    Please read more here Convert []string to []interface{}

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题