Basic Syntax in Go
In this tutorial, we will learn the basic syntax of Go language. We will go through the key components of a simple Go program.
Go Program
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Output
Hello, World!
Basic Syntax of a Go Program
package main
This line declares the package name. In Go, every program is part of a package, andmain
is a special package name that tells the compiler this is the entry point of the program.import "fmt"
This line imports thefmt
package, which contains functions for formatted I/O, including printing to the console.func main()
This line defines the main function, which is the entry point of the program. Thefunc
keyword is used to declare a function.{
This opening brace marks the beginning of the main function's body.fmt.Println("Hello, World!")
This line prints the string "Hello, World!" to the standard output (usually the screen). ThePrintln
function is part of thefmt
package and prints the provided text followed by a new line.}
This closing brace marks the end of the main function's body.
Key Points to Remember
- All Go statements must end without a semicolon (
;
), though semicolons are automatically inserted at the end of each line. - The main function is the entry point of a Go program.
- Comments can be added using
//
for single-line comments or/* ... */
for multi-line comments. - Code blocks are enclosed in curly braces
{}
. - Go is case-sensitive, meaning that
Main
andmain
would be considered different identifiers.