bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Go/Go Tutorial
Go•Go Tutorial

Go Syntax

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!");}

Previous

Go Getting Started

Next

Go Comments

This chapter

Overview
39

Lessons

95m

Read time

1. Go Tutorial2. Go Introduction3. Go Getting Started4. Go Syntax5. Go Comments6. Go Variables7. Go Multiple Variable Declaration8. Go Variable Naming Rules9. Go Constants10. Go Output Functions11. Go Formatting Verbs12. Go Data Types13. Go Boolean Data Type14. Go Integer Data Types15. Go Float Data Types16. Go String Data Type17. Go Arrays18. Go Slices19. Go Access, Change, Append and Copy Slices20. Go Operators21. Go Arithmetic Operators22. Go Assignment Operators23. Go Comparison Operators24. Go Logical Operators25. Go Bitwise Operators26. Go Conditions27. Go if statement28. Go if else Statement29. Go else if Statement30. Go Nested if Statement31. Go switch Statement32. Go Multi-case switch Statement33. Go For Loops34. Go Functions35. Go Function Parameters and Arguments36. Go Function Returns37. Go Recursion Functions38. Go Struct39. Go Maps

On this page

Example explainedGo StatementsGo Compact Code