如何在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?

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

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

Yep. An example:

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

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

    print(split...)
}

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

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