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:])
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改