A Go program consists of several key components arranged in a structured way. These components include:
- Package Declaration: This defines the package to which the file belongs.
- Importing Packages: External functionalities are made available by importing relevant packages.
- Functions: These are blocks of reusable code designed to perform specific tasks.
- Statements and Expressions: These provide the logic and instructions executed by the program.
Example:
Go
x
package main
import ("fmt")
func main() {
fmt.Println("Hello World!")
}
Explanation of the Example Code
- Package Declaration (Line 1): In Go, every program is part of a package. This is declared using the
package
keyword. The file belongs to themain
package, which is mandatory for any Go program meant to be executed. - Import Statement (Line 2): The
import ("fmt")
statement allows access to thefmt
package. This package provides various functions for text formatting and printing. - Whitespace (Line 3): Go ignores extra white space. A blank line, such as this one, is used to improve the readability of the code.
- Main Function (Line 4): The
func main() {}
defines the main function. This is the starting point of any Go program. The code enclosed within{}
is executed when the program runs. - Statement (Line 5): The
fmt.Println()
function from thefmt
package is used to print text to the console. In this case, it displays “Hello World!” when executed.
Go Statements and Syntax Rules
- A statement in Go, like
fmt.Println("Hello World!")
, represents a complete instruction for the program to execute. - Statements can terminate with a newline (pressing Enter) or a semicolon (
;
). However, in Go, semicolons are implicitly added at the end of a statement, so they are rarely seen in the source code. - Curly Brackets Placement: The opening
{
must be on the same line as the function declaration.
Example of Incorrect Syntax:
Go
package main
import ("fmt")
func main()
{
fmt.Println("Hello World!")
}
This code will throw an error because the {
is placed on a new line, violating Go’s syntax rules.
Compact Go Code
Although Go allows all code to be written on a single line, this approach is strongly discouraged, as it can reduce readability.
Example of Compact Code:
Go
package main; import ("fmt"); func main() { fmt.Println("Hello World!"); }
While the above code runs correctly, it’s harder to read and should be avoided in practice.