Simple Golang Program
Golang programs can be written in a very easy manner, follow the below two steps to create, compile and run the program.
1. Open a text editor, write the following SampleProgram program and save the file with .go extension i.e. SampleProgram.go
Sample Golang Program - SampleProgram.go
package main
import "fmt"
func main() {
// Declare and Initialize an integer variable 'age' with value 6
var age int = 6
// Print the local variable 'age' in the console window
fmt.Println(age)
}
File Name: In Golang, each file should be responsible for a single package and the file should have an extension .go i.e. SampleProgram.go
Identifiers: An Identifier is a name of a class, interface or a variable. The identifier should be unique within the package or the block scope level along with the hierarchy. In our example SampleProgram.go, we are having the following identifiers
- main - Name of the package
- main - Name of a method
- age - Name of the local variable
Keywords: A keyword is a reserved word by Golang, so we can't use those words as an identifier and each keyword has its own functionality. In our SampleProgram.go example, we are having the following keywords
- package - Specifies the Package
- import - Specifies the Package to be import to the current program
- func - Specifies the function
- var - Specifies the variable declaration
- int - Specifies its an Integer data type
main function - Go program requires an entry point to start the execution. The main method func main() is the default entry point method to start the execution and it should be under a package main.
Note: Golang program may have one or more package, but only one package will have a main method and that package name should be main.
Statements - In our example we are having two statements in our main method such as
- var age int = 6 - Its a Declaration Statement and initialized with value 6.
- fmt.Println(age) - Its a method invoking statement, it invokes the predefined method println belongs to the package fmt which was imported in the top of the function and prints the argument value into the console window (i.e. 6)
Semicolon - The basic rule in Golang is the declaration, expression and invoking statements may or may not end with a semicolon in otherwords semicolon is an optional to end up a statement.;.
Block Scope { } - Open and close curly braces or curly brackets groups a set of statements and its called as Block scope.
- Block scope in function func main { } - The statements which is inside the curly braces or curly brackets are belongs to the specified function main
Note: The basic rule in Go programming is the open curly braces should be start in the same line of the function, conditional statements, etc., otherwise it will throw a compiler error.