dpxnrx11199 2018-12-21 01:14
浏览 22
已采纳

将切片传播为args列表

I have this func:

func Middleware(adapters ...interface{}) http.HandlerFunc {
    // ...
}

and I am trying to call it via:

middleware := []mw.Adapter{mw.Error(),mw.Auth("x-huru-api-token")}
router.HandleFunc("/person_data_field", 
mw.Middleware(middleware...,h.makeGetMany(v))).Methods("GET")

this doesn't compile though, I get:

enter image description here

In any case, I need to spread the slice so that it is sent as multiple arguments not just one arg...

With JS, it just looks like this:

const v = [1,2,3];

const f = function(...values){
    console.log(values);  // [1,2,3,4]
};

f(...v,4);
  • 写回答

1条回答 默认 最新

  • dsjpik057730 2018-12-21 01:29
    关注

    You can pass variadic arguments individually or as a single slice. You cannot mix and match. The slice element type must match the variadic argument type.

    To fix the problem, put all of the variadic arguments in a slice of []interface{}:

    middleware := []interface{}{mw.Error(),mw.Auth("x-huru-api-token"), h.makeGetMany(v)}
    router.HandleFunc("/person_data_field", mw.Middleware(middleware...)).Methods("GET")
    

    Use slice tricks if you cannot build the slice directly as shown in the previous snippet.

    middleware := []mw.Adapter{mw.Error(),mw.Auth("x-huru-api-token")}
    router.HandleFunc("/person_data_field", mw.Middleware(
        append(append([]interface{}{}, middleware...), h.makeGetMany(v)))).Methods("GET")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏