gpt4 book ai didi

go - 如何将 slice 作为可变参数输入?

转载 作者:行者123 更新时间:2023-12-01 22:24:46 24 4
gpt4 key购买 nike

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

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

    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")



例如,
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))
}

输出:
hello world

关于go - 如何将 slice 作为可变参数输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60741492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com