我如何通过切片作为可变参数输入? [英] How can I pass a slice as a variadic input?

查看:84
本文介绍了我如何通过切片作为可变参数输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数 func more(... t)。我想知道是否可以使用slice来填充 ... 参数列表。

我试图解决下面的程序。基本上模仿一个正常的shell接收命令作为一个字符串。
命令功能需要一个列表的参数,我不看看我可以如何将一个字符串转换成这样的列表

pre $ import $ os $ exec $ b $ import $ strings
func main(){
plainCommand:=echo hello world
sliceA:= strings.Fields(plainCommand)
cmd:= exec.Command(sliceA)
}


解决方案


Go编程语言规范



将参数传递给...参数

如果f是最终参数类型的可变参数... T,那么在
函数中,参数等价于类型为[] T的参数。在
每次调用f时,传递给最终参数的参数是一个新的
类型的[] T切片,其连续元素是实际参数,
,它们都必须可以分配给类型T.切片的长度是
,因此绑定到最终参数的参数数量可能不同,并且每个调用站点可能
不同。





Package exec < a>



func命令


$ b $

  func命令(name string,arg ... string)* Cmd 

命令返回Cmd结构来执行命名程序,给定参数



返回的Cmd Args字段由命令名称
后跟arg元素构成,因此arg不应包含命令
名称本身。例如,Command(echo,hello)






例如,

 包主

导入(
fmt
os / exec


func main(){
name:=echo
args:= [] string {hello,world}
cmd:= exec.Command(name,args ...)
out,err:= cmd.Output()
if err!= nil {
fmt.Println(err )
}
fmt.Println(string(out))
}

输出:

  hello world 


I have a function func more(... t). I'm wondering if it's possible to use a slice to populate a list of arguments ... .

I'm trying to solve the following program. Basically to mimic a normal shell which receives the command as a string. Command function requires a "list" of arguments and I don't see how I can convert a string into a such list

    import "os/exec"
    import "strings"
    func main(){
        plainCommand  := "echo hello world"
        sliceA := strings.Fields(plainCommand)
        cmd := exec.Command(sliceA)
    }

解决方案

The Go Programming Language Specification

Passing arguments to ... parameters

If f is variadic with final parameter type ...T, then within the function the argument is equivalent to a parameter of type []T. At each call of f, the argument passed to the final parameter is a new slice of type []T whose successive elements are the actual arguments, which all must be assignable to the type T. The length of the slice is therefore the number of arguments bound to the final parameter and may differ for each call site.


Package exec

func Command

func Command(name string, arg ...string) *Cmd

Command returns the Cmd struct to execute the named program with the given arguments.

The returned Cmd's Args field is constructed from the command name followed by the elements of arg, so arg should not include the command name itself. For example, Command("echo", "hello")


For example,

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    name := "echo"
    args := []string{"hello", "world"}
    cmd := exec.Command(name, args...)
    out, err := cmd.Output()
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(string(out))
}

Output:

hello world

这篇关于我如何通过切片作为可变参数输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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