Hello World
Running the "Hello World" program in golang
Last updated
Running the "Hello World" program in golang
Last updated
Our first program will be the classic "hello world" program. To run this in go, create a new file called hello.go On MacOS create the file by running
$ touch hello.go
Open the file in your favorite text editor (or VSCode which we will be using in this documentation), and paste the following code into it:
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
Save the file, and in your terminal, run the following command to execute the file
$ go run hello.go
# this will output: hello world
In the code above, line 1
is the package declaration name. Go links all the packages during runtime for program execution beginning with the main
package. The main
function is also important here since this is where program execution begins. That is, the main function is the function that is called whenever we run a golang program file.
As per the golang language specs:
The main package must have package name
main
and declare a functionmain
that takes no arguments and returns no value.func main() { … }
Program execution begins by initializing the main package and then invoking the function
main
. When that function invocation returns, the program exits.
The second bit worth pointing out is the import "fmt"
line. fmt
is short for format, and it is a package that implements I/O formatting, similar to the printf
and scanf
implemented in the C programming language. It even uses the same formatting verbiage as C. That is, %s
for strings, %d
for integers, and so on. See a full list of the verbs here: https://pkg.go.dev/fmt
For the next section, we will go over the basic data types in golang.