We can only have the traditional hello world code as the first code to see things working.
Let's then create a folder inside the src folder we have defined in the previous setup article:
take ~/go/src/hello-world
Go files, has extension .go. So, we can create our first file:
touch hello.go
This file will be the only module and entry point of this program. Let's start with a traditional "main" function:
func main(){
}
This function could be called anything. There's no strictness regarding its name.
Finally, we have to inform Go that the function main will be the start point of our program. We use the keyword package and define our function name to do that.
package main
func main(){
}
One thing I notice is that Go doesn't like semicolons. We can have it, but every time I save the code in my VSCode (using the extension), it formats, and the formatter removes all semicolons.
console.log-ish
We don't have global APIs in Go, so we can't straight use them without import.
If we want to print out something, we can't simply console.log. Instead, we need to import a package that provides this API, and then we have it available.
The package responsible for implementing IO in Go is called fmt. Let's import it:
package main
import "fmt"
func main(){
}
Simply importing it in this file will be already available in this context, so we can use it. I'm not sure if it's always like this, but I'll figure it out later.
For now, I know that fmt will be available and with auto-completion in my editor.
The method we want to console something is the Println (classic name):
package main
import "fmt"
func main() {
fmt.Println("Hello World")
}
Note that the method starts with uppercase P. It seems a convention in Go APIs.
Running
Now that we have this file, we can simply run. We have first to compile it and then run the binary.
To compile it, we use the command build from Go CLI:
go build hello.go
Now, to run we simply call it:
./hello
# Hello world
Luckily Go provides a shortcut that compiles and runs the executable within a single command:
go run hello.go
# Hello world
Conclusion
So far, nothing too complex. The similarity with JS is significant til this point, and it makes me see the inspiration Deno has in terms of modules and APIs.