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 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答