doujianqin5172 2019-08-01 13:37
浏览 23
已采纳

如何在接口声明[golang]中扩展数组?

i have this function declaration and i want return array of interface.
spread(1,2,3) => [4,5,6].
i also searched any place like play.golang,other stackoverflow go tags but nothing found

func spread2(a ...interface{}) []interface{} {
        a:=[]int{4,5,6}
        return []interface{}{a}//[[4,5,6]] NO

        return []interface{}{a...} //[4,5,6] YES,i want this; 
                                   //but got error
}

the error i got is : syntax error: unexpected ..., expecting comma or }

  • 写回答

2条回答 默认 最新

  • dorv56831 2019-08-05 22:58
    关注

    in my case []interface{} input is same as output.
    so just return any thing as array is ok

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dptpn06684 2019-08-01 13:51
    关注

    For example,

    package main
    
    import (
        "fmt"
    )
    
    func spread(a ...interface{}) []interface{} {
        return a
    }
    
    func main() {
        fmt.Println(spread(1, 2, 3))
    }
    

    Playground: https://play.golang.org/p/Bqgu_A1BCti

    Output:

    [1 2 3]
    

    An optimizing compiler may inline the spread function.

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于python进行多背包问题的多值编码
  • ¥15 相同型号电脑与配置,发现主板有一台貌似缺少了好多元器件似的,会影响稳定性和使用寿命吗?
  • ¥15 要求编写稀疏矩阵A的转置矩阵的算法
  • ¥15 编写满足以下要求的停车场管理程序,设停车场只有一个可停放n辆车的狭窄通道且只有一个大门可供车辆进出。
  • ¥15 C语言:数据子序列基础版
  • ¥20 powerbulider 导入excel文件,显示不完整
  • ¥15 用keil调试程序保证结果进行led相关闪烁
  • ¥15 paddle训练自己的数据loss降不下去
  • ¥20 用matlab的pdetool解决以下三个问题
  • ¥15 单个福来轮的平衡与侧向滑动是如何做到的?