First, you need to download and install Go from the official website ( https://golang.org/dl/) . The installation process varies depending on your operating system.
After installation, open your terminal and run the following command to verify the installation:
go version
If the installation is successful, it will display the installed Go version.
Create a directory for your Go projects. By convention, the workspace has three sub - directories: src
, pkg
, and bin
.
mkdir go_workspace
cd go_workspace
mkdir src pkg bin
Set the GOPATH
environment variable to point to your workspace directory. For example, in a Unix - like system:
export GOPATH=$HOME/go_workspace
Here is a simple “Hello, World!” program in Go:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
To run this program, save it as hello.go
and run the following command in the terminal:
go run hello.go
In Go, you can declare variables in two ways:
package main
import "fmt"
func main() {
// Explicit declaration
var age int
age = 25
// Short variable declaration
name := "John"
fmt.Printf("Name: %s, Age: %d\n", name, age)
}
package main
import "fmt"
func main() {
num := 10
if num > 5 {
fmt.Println("Number is greater than 5")
} else {
fmt.Println("Number is less than or equal to 5")
}
}
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Println(i)
}
}
package main
import "fmt"
func main() {
day := "Monday"
switch day {
case "Monday":
fmt.Println("It's Monday")
case "Tuesday":
fmt.Println("It's Tuesday")
default:
fmt.Println("It's some other day")
}
}
package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func main() {
result := add(3, 5)
fmt.Println("The sum is:", result)
}
package main
import "fmt"
func main() {
var numbers [5]int
numbers[0] = 1
numbers[1] = 2
fmt.Println(numbers)
}
package main
import "fmt"
func main() {
slice := []int{1, 2, 3, 4, 5}
fmt.Println(slice)
}
package main
import "fmt"
func main() {
person := map[string]string{
"name": "Alice",
"city": "New York",
}
fmt.Println(person)
}
package main
import "fmt"
func changeValue(num *int) {
*num = 100
}
func main() {
num := 20
changeValue(&num)
fmt.Println(num)
}
Go has built - in support for concurrency using goroutines and channels.
package main
import (
"fmt"
"time"
)
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Printf("Worker %d started job %d\n", id, j)
time.Sleep(time.Second)
fmt.Printf("Worker %d finished job %d\n", id, j)
results <- j * 2
}
}
func main() {
const numJobs = 5
jobs := make(chan int, numJobs)
results := make(chan int, numJobs)
// Start up 3 workers
const numWorkers = 3
for w := 1; w <= numWorkers; w++ {
go worker(w, jobs, results)
}
// Send jobs
for j := 1; j <= numJobs; j++ {
jobs <- j
}
close(jobs)
// Collect results
for a := 1; a <= numJobs; a++ {
<-results
}
close(results)
}
package main
import (
"errors"
"fmt"
)
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}
Use gofmt
to format your code. It ensures that all Go code follows a consistent style.
gofmt -w your_file.go
Write unit tests for your functions using the testing
package.
package main
import "testing"
func add(a, b int) int {
return a + b
}
func TestAdd(t *testing.T) {
result := add(2, 3)
if result != 5 {
t.Errorf("add(2, 3) = %d; want 5", result)
}
}
To run the test, save it as add_test.go
and run:
go test
Use comments to document your code. You can also generate documentation using godoc
.
In this step - by - step guide, we have covered the essential concepts of Golang for new programmers. We started with setting up the environment, then explored basic syntax, control structures, functions, data structures, pointers, concurrency, and error handling. We also discussed common practices and best practices such as code formatting, testing, and documentation. With these fundamentals, you are well on your way to becoming a proficient Go programmer.