Go Programming: Hello World
Writing Your First Go Program
Go (or Golang) is a powerful and efficient programming language designed by Google. It is known for its simplicity, concurrency support, and fast execution. Let's begin our Go journey with the most basic program: "Hello, World!"
Code Example:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Understanding the Code
Let's break down each part of the program:
1. Package Declaration
package main
Every Go program starts with a package declaration. The main
package is special—it defines an executable program. If you don’t use main
, the program won’t run as a standalone application.
2. Importing Packages
import "fmt"
Go uses the import
keyword to bring in external packages. The "fmt"
package (short for format) provides functions for formatting text, including printing to the console.
3. Defining the main
Function
func main()
The main()
function is the entry point of every Go program. When you run the program, execution starts from this function.
4. Printing to the Console
fmt.Println("Hello, World!")
fmt.Println()
prints a message to the console."Hello, World!"
is a string, andPrintln()
outputs it with a newline.
Running the Program
Once you've saved your code in main.go
, open a terminal and run:
go run main.go
This command compiles and executes the program, displaying:
Hello, World!
Summary
- Every Go program must have a
main
package and amain()
function. - The
fmt
package is used for printing output. go run
is used to execute the program.
This is the foundation of Go programming. Next, we'll explore variables and data types!