Flash cards
Review the key moves
What is the main idea behind Go Syntax?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
___ mainPut the learning moves in the order that makes the concept easiest to apply.
A Go file consists of the following parts:
- Package declaration
- Import packages
- Functions
- Statements and expressions
Look at the following code, to understand it better:
Example
package main
import ("fmt")
func main() {
fmt.Println("Hello World!")
}Example explained
Line 1: In Go, every program is part of a package. We define this using the package keyword. In this example, the program belongs to the main package.
Line 2: import ("fmt") lets us import files included in the fmt package.
Line 3: A blank line. Go ignores white space. Having white spaces in code makes it more readable.
Line 4: func main() {} is a function. Any code inside its curly brackets {} will be executed.
Line 5: fmt.Println() is a function made available from the fmt package. It is used to output/print text. In our example it will output "Hello World!".
Note
In Go, any executable code belongs to the main package.
Go Statements
fmt.Println("Hello World!") is a statement.
Hitting the Enter key adds " ; " to the end of the line implicitly (does not show up in the source code).
The left curly bracket { cannot come at the start of a line.
Run the following code and see what happens:
Example
package main
import ("fmt")
func main() {
fmt.Println("Hello World!")
}Go Compact Code
You can write more compact code, like shown below (this is not recommended because it makes the code more difficult to read):
Example
package main; import ("fmt"); func main() { fmt.Println("Hello World!");}