dsz7121 2019-07-08 00:42
浏览 52
已采纳

用于将多个“参数”映射到单个可变参数的习惯用法

Is there a way to use a combination of splatted arguments and simple arguments (defined below) in a function taking a variadic parameter in golang? If not, is there a well-known idiom that approximates this feature? If possible, is there an idiom approximating this feature that does not require repeating the type name?


Suppose I have a function with a variadic parameter in golang of type ...T. It seems like your options at the call site are limited to:

  • multiple simple arguments, each of type T, i.e. f(…… x1, x2, x3 ……)
  • a single splatted argument of type []T, i.e f(…… ...xs ……)

In some other languages like Python, it is possible to capture a combination of simple arguments and splatted arguments with a variadic parameter:

$ python
>>> def foo(*args): return args
... 
>>> foo(1, 2, *[3, 4])
(1, 2, 3, 4)

However, the same thing does not appear to work in go.

// splat.go
package main

import "os"
import "fmt"

func write(args ...string) {
        for _, item := range args {
                fmt.Printf("%s
", item)
        }
}

func main() {
        write("foobarbaz", os.Args[1:]...)
}

from the error message, it's clear that the splatted argument and the simple argument are not being mapped to the same parameter.

$ go run splat.go 
# command-line-arguments
./splat.go:14: too many arguments in call to write
  • 写回答

1条回答 默认 最新

  • dsg41888 2019-07-08 01:13
    关注

    Create a slice with all of the arguments and splat that slice.

    write(append([]string{"foobarbaz"}, os.Args[1:]...)...)
    

    If the string, []string pattern is common in the application code, then consider writing a function to simplify the code at the call sites:

    func stringArgs(s string, args []string) []string { 
       return append([]string{s}, args...)
    }
    
    ...
    
    write(stringArgs("foobarbaz", os.Args[1:])...)
    

    or

    func writeStringArgs(s string, args []string) {
        write(append([]string{"foobarbaz"}, os.Args[1:]...)...)
    }
    
    ...
    
    writeStringArgs(s, os.Args[1:])
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示