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

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

问题描述

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

我正在尝试解决以下程序.基本上是模仿一个普通的shell,它以字符串的形式接收命令.Command 函数需要一个参数列表",我不知道怎么做将字符串转换为这样的列表

 导入os/exec"导入字符串"功能主(){普通命令:=回声你好世界"sliceA := strings.Fields(plainCommand)cmd := exec.Command(sliceA)}

解决方案

Go 编程语言规范

将参数传递给...参数

如果 f 是具有最终参数类型 ...T 的可变参数,则在function 参数等效于 []T 类型的参数.在每次调用 f,传递给最后一个参数的参数都是一个新的[]T 类型的切片,其连续元素是实际参数,都必须可以分配给类型 T.切片的长度是因此绑定到最终参数的参数数量可能每个呼叫站点都不同.

<小时><块引用>

包执行

func 命令

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

Command 返回 Cmd 结构以执行命名程序给定参数.

返回的 Cmd 的 Args 字段是根据命令名称构造的后跟 arg 的元素,因此 arg 不应包含命令名称本身.例如,Command("echo", "hello")

<小时>

例如

包主进口 (fmt"操作系统/执行")功能主(){名称:=回声"args := []string{"hello", "world"}cmd := exec.Command(name, args...)出,错误:= cmd.Output()如果错误!= nil {fmt.Println(err)}fmt.Println(string(out))}

输出:

你好世界

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天全站免登陆