Hello world program in Go (Golang)
Below is a simple "Hello, World!" program in Go:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Explanation:
-
Package Declaration: Every Go file begins with a package declaration. The
main
package is special—it tells Go that this file is an executable program rather than a shared library. -
Import Statement: Imports are used to include packages that provide functionality beyond the basic language features. Here, we import the
"fmt"
package, which stands for "format" and provides functions for formatting input and output. -
Main Function: The
main
function is the entry point of any Go program. It is where execution of the program begins. In this example,main()
callsfmt.Println()
to print "Hello, World!" to the console. -
fmt.Println(): This function is used to print a line to the standard output (usually the console). It takes any number of arguments and prints them, separated by spaces, followed by a newline (
\n
).
Running the Program:
To run this program:
-
Save the code to a file named
hello.go
(or any name ending with.go
). -
Open a terminal or command prompt.
-
Navigate to the directory where you saved
hello.go
. -
Run the program by typing:
go run hello.go
You should see the output:
Hello, World!
Additional Notes:
- Go uses curly braces
{}
to delimit blocks of code, similar to languages like C, Java, and JavaScript. - Statements in Go do not end with a semicolon (
;
) unless you want to put multiple statements on the same line. fmt.Println()
is just one of many functions provided by thefmt
package for formatting input and output in various ways.