将[]字符串传递给需要可变参数的函数 [英] Pass []string to a function that expects a variadic parameter

查看:114
本文介绍了将[]字符串传递给需要可变参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了不重复我的自我,我想创建一个处理运行某些命令的函数。

  func runCommand(name string,arg ... string)error {
cmd:= exec.Command(name ,arg)
if err:= cmd.Run(); err!= nil {
return err
} else {
return nil
}
}

一旦我尝试运行它,我会收到以下错误:

  can not在参数中使用arg(type [] string)作为类型字符串给exec.Command 

我看了一下执行 os。命令 ,它看起来功能签名与我提供的完全一致。



在内部,一个 []字符串应该与可变参数相同,但是对于编译器来说,它看起来不是。

有没有办法将variadic参数传递给命令

解决方案 使用另一个 ... []字符串

  cmd:= exec.Command(name,arg ...)

语言规范将参数传递给...参数


如果最后一个参数可以赋值给一个切片类型 [] T ,它可能是
传递不变作为 ... T 参数的值,如果参数是
后跟 ... 。在这种情况下,不会创建新的切片。



给定切片和调用

  s:= [] string {James,Jasmine} 
问候(goodbye:,s ...)

在Greeting中, who s 具有相同的底层数组。



In order to don't repeat my self over and over I wanted to create a function that handles running some commands.

func runCommand(name string, arg ...string) error {
    cmd := exec.Command(name, arg)
    if err := cmd.Run(); err != nil {
        return err
    } else {
        return nil
    }
}

Once I try to run this I get the following error:

cannot use arg (type []string) as type string in argument to exec.Command

I had a look into the implementation of the os.Command and it looks that the function signature is exact what I supply.

Internally a []string should be the same as variadic parameter but for the compiler it seems not.

Is there a way to pass the variadic parameter into the Command?

解决方案

You expand the []string with another ...

cmd := exec.Command(name, arg...)

From the language spec on Passing arguments to ... parameters

If the final argument is assignable to a slice type []T, it may be passed unchanged as the value for a ...T parameter if the argument is followed by .... In this case no new slice is created.

Given the slice s and call

s := []string{"James", "Jasmine"}
Greeting("goodbye:", s...)

within Greeting, who will have the same value as s with the same underlying array.

这篇关于将[]字符串传递给需要可变参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆