Steven Lu
Steven Lu

Reputation: 2180

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

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?

Upvotes: 3

Views: 3962

Answers (4)

Dave
Dave

Reputation: 4694

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

Upvotes: 6

Arjan
Arjan

Reputation: 21505

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:]...)

Upvotes: 6

Tyson
Tyson

Reputation: 541

Yep. An example:

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

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

    print(split...)
}

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

Upvotes: 0

Kavu
Kavu

Reputation: 8394

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

Upvotes: 0

Related Questions