Printing Several Things
Mix text and variables in one line, the Go way.
1package main
2
3import "fmt"
4
5func main() {
6 name := "Ada"
7 age := 10
8 fmt.Println(name, "is", age, "years old")
9}
$ go run main.go
Ada is 10 years old
Every line, explained
package main- Every Go file starts by saying which package it belongs to. package main means "this is a program you can run", and Go will look inside it for func main.
import "fmt"- import brings in a package from Go's standard library. "fmt" (short for format) is the one full of printing tools, like fmt.Println.
func main() {- func main() { ... } is where a Go program starts. When you run the program, Go finds func main inside package main and runs everything between its braces, top to bottom.
name := "Ada"- := is Go's declare-and-assign: it creates a new variable AND stores a value in one step, and Go works out the type by itself. You will use := constantly in Go. (No semicolon needed; Go adds them for you behind the scenes.)
age := 10- := is Go's declare-and-assign: it creates a new variable AND stores a value in one step, and Go works out the type by itself. You will use := constantly in Go. (No semicolon needed; Go adds them for you behind the scenes.)
fmt.Println(name, "is", age, "years old")- fmt.Println can take several values separated by commas, and it prints them all on one line with a single space between each. This is the easy Go way to mix variables into a message.
}- This closing brace } ends func main.