In this version, you’ll declare a variable first, then assign a value to it:
package mainimport ( "fmt" "os")func main() { var name string // assign a new value to the string variable name = os.Args[1] fmt.Println("Hello great", name, "!") // changes the name, declares the age with 85 name, age := "gandalf", 85 fmt.Println("My name is", name) fmt.Println("My age is", age) fmt.Println("BTW, you shall pass!")}
Simplify the code using short variable declaration:
package mainimport ( "fmt" "os")func main() { // assign a new value using short declaration name := os.Args[1] fmt.Println("Hello great", name, "!") // changes the name, declares the age with 85 name, age := "gandalf", 85 fmt.Println("My name is", name) fmt.Println("My age is", age) fmt.Println("BTW, you shall pass!")}
The os.Args variable is a slice of strings that contains:
os.Args[0] - Path to the running program
os.Args[1] - First command-line argument
os.Args[2] - Second command-line argument
And so on…
// Print all argumentsfmt.Printf("%#v\n", os.Args)// Get the first argumentfmt.Println("1st argument:", os.Args[1])// Get the number of argumentsfmt.Println("Items inside os.Args:", len(os.Args))
// Declaration: Creates a variablevar name string// Assignment: Gives it a valuename = "Alice"// Short declaration: Does both at oncename := "Alice"
Multiple Variable Assignment
// Assign multiple variables at oncename, age := "gandalf", 85// At least one variable must be new when using :=// Here, 'age' is new, so we can redeclare 'name'
This simple version doesn’t check if an argument was provided. If you run it without arguments, it will crash! You’ll learn how to handle this with error checking later.