/usr/local
using the following command:sudo tar -C /usr/local -xzf go1.xx.x.linux - amd64.tar.gz
- Then add `/usr/local/go/bin` to your `PATH` environment variable in your shell profile (e.g., `~/.bashrc` or `~/.zshrc`):
export PATH=$PATH:/usr/local/go/bin
Go
binary directory is added to your system’s PATH
environment variable.A Go workspace is a directory hierarchy with three main directories:
src
: Contains Go source files organized by package.pkg
: Contains compiled package objects.bin
: Contains executable binaries.You can create a workspace directory and set the GOPATH
environment variable to point to it. For example:
mkdir ~/go - workspace
export GOPATH=~/go - workspace
Here is a simple “Hello, World!” program in Go:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
package main
: Every Go program must belong to a package. main
is a special package that indicates an executable program.import "fmt"
: Imports the fmt
package, which provides functions for formatted input and output.func main()
: The main
function is the entry point of a Go program.fmt.Println("Hello, World!")
: Calls the Println
function from the fmt
package to print a line of text to the console.In Go, you can declare variables in two ways:
var age int
age = 25
name := "John"
int
, int8
, int16
, int32
, int64
, uint
, uint8
, uint16
, uint32
, uint64
, float32
, float64
.var num1 int = 10
var num2 float64 = 3.14
message := "This is a string"
isValid := true
age := 20
if age >= 18 {
fmt.Println("You are an adult.")
} else {
fmt.Println("You are a minor.")
}
for i := 0; i < 5; i++ {
fmt.Println(i)
}
day := 3
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
default:
fmt.Println("Other day")
}
func add(a int, b int) int {
return a + b
}
func main() {
result := add(3, 5)
fmt.Println(result)
}
func divide(a int, b int) (int, int) {
quotient := a / b
remainder := a % b
return quotient, remainder
}
func main() {
q, r := divide(10, 3)
fmt.Printf("Quotient: %d, Remainder: %d\n", q, r)
}
Suppose you have a file mathutils.go
with the following content:
package mathutils
func Add(a int, b int) int {
return a + b
}
In another file, you can import and use the mathutils
package:
package main
import (
"fmt"
"mathutils"
)
func main() {
result := mathutils.Add(2, 3)
fmt.Println(result)
}
In Go, errors are values. Functions that can potentially return an error usually return it as the last return value.
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Open("nonexistent.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
fmt.Println("File opened successfully.")
}
Go has built - in support for concurrency using goroutines and channels.
A goroutine is a lightweight thread of execution.
package main
import (
"fmt"
"time"
)
func sayHello() {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println("Hello")
}
}
func main() {
go sayHello()
for i := 0; i < 5; i++ {
time.Sleep(200 * time.Millisecond)
fmt.Println("World")
}
}
Channels are used to communicate and synchronize between goroutines.
package main
import (
"fmt"
)
func sum(s []int, c chan int) {
sum := 0
for _, v := range s {
sum += v
}
c <- sum
}
func main() {
s := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)
x, y := <-c, <-c
fmt.Println(x, y, x+y)
}
Use gofmt
to format your Go code automatically. For example:
gofmt -w your_file.go
Always check for errors returned by functions. Don’t ignore them.
Write unit tests for your code using the testing
package in Go. For example:
package mathutils
import "testing"
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Add(2, 3) = %d; want 5", result)
}
}
In this blog, we have covered the fundamental concepts of Golang, including installation, basic syntax, variables, data types, control structures, functions, packages, error handling, and concurrency. We also discussed common practices and best practices for writing high - quality Go code. With this knowledge, you are well - equipped to start building your own Go applications. As you continue to learn and practice, you will discover more advanced features and techniques that make Go a powerful and versatile programming language.