Nick
Nick

Reputation: 9041

How to print os.args[1:] without braces in Go?

When I tried to print command line arguments using

    fmt.Println(os.Args[1:])

I got result like

[Gates Bill]

How can I get rid of the [] around the arguments? And Go seems to eat all the commas in the arguments, how can I get the output like

Last name, First name
Gates, Bill

Upvotes: 1

Views: 2659

Answers (2)

Chandra Sekar
Chandra Sekar

Reputation: 10843

You should use strings.Join for this. Try,

fmt.Printf("%s, Author of The Art of Computer Programming", strings.Join(os.Args[1:], ", "))

Join returns a string with ", " inserted between each argument.

Upvotes: 10

Ozzadar
Ozzadar

Reputation: 538

The reason it's outputting the brackets is because you're passing a slice into the print command.

What you want to do is take each command and put them into a string to be printed as needed.

firstname := os.Args[1]
lastname := os.Args[2]
fmt.Println(lastname + ", " + firstname)

You should also take a look at the strings package as was pointed out by Chandru. There's a bunch of goodies in there to help with dealing with strings.

See: https://golang.org/pkg/strings/

Upvotes: 1

Related Questions