jjspscl.

DAY 1 of Learning Go: Hello World

Neovim and Go

My current Neovim is barebone straight from brew. So I will be kickstarting it and adding gopls with mason.

a go "module"

GoMaking a hello world program is relatively simple to setup

First, I have to initialize a go project with go module init hello_world and it creates this file:

// go.mod 
module hello_word

go 1.22.2

Apparently this makes the current directory a Go Project, and I'm going to learn more about modules(?) later on.

Each Go module is defined by a go.mod file that describes the module’s properties, including its dependencies on other modules and on versions of Go. - go.mod file reference

go build(ing a hello world program)

Once the project is initialized I went on creating a hello.go file:

package main

import "fmt"


func main() {
	fmt.Println("Hello, World!")
}

Some quick notes:

  • first line contains the package declaration

  • in a Go module, code can be organized by one or more packages

    • the main package in a Go module, contains the code that starts a Go program

  • next line are import declarations

  • Go programs starts from the main function like other languages like Java & C and uses braces to mark function start-ends

  • fmt implements formatted I/O with functions analogous to C's printf and scanf. The format 'verbs' are derived from C's but are simpler.

    • Println basically prints out data passed to it

After saving the file I went back to my terminal and executed:

$ go build

Which creates a hello_word executable, in my case a unix executable (But apparently creates an .exe file on W*ndows) in the current directory.

And once I run it the hello world prints as expected:

$ go ./hello_world
Hello, world!

If in any case I want to change the output's executable name I pass in -o flag like so:

$ go build -o hewo