How do I split a string and use it as function arguments in Go?

huangapple go评论142阅读模式
英文:

How do I split a string and use it as function arguments in Go?

问题

我有一个由空格分隔的字符串,在这个例子中,它是一个命令:ls -al

Go语言有一个名为exec.Command的方法,需要将这个命令作为多个参数传递,我可以这样调用它:exec.Command("ls", "-al")

有没有一种方法可以将任意字符串按空格分割,并将其所有的值作为参数传递给这个方法?

英文:

I have a string that is separated by spaces, in this example, its a command: ls -al.

Go has a method exec.Command that needs to accept this command as multiple arguments, I call it like so: exec.Command("ls", "-al")

Is there a way to take a arbitrary string, split it by spaces, and pass all of its values as arguments to the method?

答案1

得分: 6

你可以使用foo...的方式,将任何[]T类型的参数传递给类型为...T的参数,其中foo的类型为[]Tspec

exec.Command的类型为:

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

在这种情况下,你需要直接传递第一个参数(name),然后使用...展开剩余的参数:

args := strings.Fields(mystr) //或者任何类似的分割函数
exec.Command(args[0], args[1:]...)
英文:

You can pass any []T as a parameter of type ...T using foo... where foo is of type []T: spec

exec.Command is of type:

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

In this case you will have to pass 1st argument (name) directly and you can expand the rest with ...:

args := strings.Fields(mystr) //or any similar split function
exec.Command(args[0], args[1:]...)

答案2

得分: 3

我最近发现了一个很好的软件包,可以像shell一样处理字符串的拆分,包括处理引号等等:https://github.com/kballard/go-shellquote

英文:

I recently discovered a nice package that handles splitting strings exactly as the shell would, including handling quotes, etc: https://github.com/kballard/go-shellquote

答案3

得分: 0

我可以回答你问题的第一部分——参见strings.Fields

英文:

I can answer the first part of your question — see strings.Fields.

答案4

得分: 0

是的。一个例子:

func main() {
    arguments := "arg1 arg2 arg3"

    split := strings.Split(arguments, " ")

    print(split...)
}

func print(args...string) {
    fmt.Println(args)
}
英文:

Yep. An example:

func main() {
	arguments := "arg1 arg2 arg3"

	split := strings.Split(arguments, " ")

	print(split...)
}

func print(args...string) {
	fmt.Println(args)
}

huangapple
  • 本文由 发表于 2014年1月27日 05:41:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/21369627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定