Golang Basics π
Welcome to the Go world! This doc will help you get started with installing Go and understanding the basics of the language's structure.
π§ Installing Go
π Linux (Debian/Ubuntu)
sudo apt update
sudo apt install golang-go
π§± Arch-based Linux (like Manjaro, EndeavourOS, etc.)
sudo pacman -S go
π macOS (using Homebrew)
brew install go
πͺ Windows
- Download the installer from: https://go.dev/dl
- Run the installer and follow the prompts.
- Restart your terminal and verify with:
go version
π Environment Setup
Make sure GOPATH
and GOROOT
are correctly configured.
For most setups, adding this to your .bashrc
or .zshrc
helps:
export PATH=$PATH:/usr/local/go/bin
For Arch-based systems installed via pacman, this is usually set correctly by default.
π Hello, World! Example
package main
import "fmt"
func main() {
fmt.Println("Hello, Go!")
}
π Explaining the Syntax
package main
This tells Go that this is an executable program (not a shared library). When a Go program is compiled, it looks for package main
and executes the main()
function.
import
Used to bring in standard or external packages. For example:
import "fmt" // "fmt" provides formatted I/O
You can import multiple packages like this:
import (
"fmt"
"math"
)
func main()
This is the entry point of the program. Go will automatically look for the main
function and execute it.
π Other Common Basics
Variables
var x int = 5
y := 10 // short declaration
Constants
const pi = 3.14
Functions
func add(a int, b int) int {
return a + b
}
If / Else
if x > y {
fmt.Println("x is bigger")
} else {
fmt.Println("y is bigger")
}
Switch
switch x {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
default:
fmt.Println("Other")
}
βΆοΈ Running & Compiling Go Code
Run a Go file directly:
go run filename.go
Compile a Go file into a binary:
go build filename.go
This will create an executable binary with the same name as the file (without the .go
extension).
β Verifying Installation
go version
To check your Go environment:
go env
π§ Pro Tip
- Go files end with
.go
- File name doesnβt need to match the function name
- Thereβs no semicolon required at the end of lines (unless you're writing multiple statements on one line)
Stay curious, and Go build cool stuff! π