After you read the article about init mod. You can create a project first to create this hello world program. Read the article init mod if you still don't know how to create a module/project in Golang.
Writing Hello World in Golang
To create a Hello World program in Golang, create a file with the extension .go (example hello.go), and add the following code:
// hello.go
main package
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Let's understand the main parts of the code:
- package main: Every Go program starts with a package declaration . The main package is a special package that indicates that this is the main program that can be run.
- func main() { ... }: Every Go program must have a main function. This function is the entry point for program execution.
- fmt.Println("Hello, World!"): This is a statement that prints the text "Hello, World!" to the console. The Println function will add a new line after printing the text.
Running the Program
After saving the file with the name hello.go, open the terminal, navigate to the directory where the file is stored, and run the following command:
go run hello.go
You will see the output:
Hello, World!
Congratulations! You've just written and run your first Hello World program in Golang. This program may be simple, but it is an important first step in understanding the basics of this powerful programming language. Enjoy exploring Golang!