Go Programming Language Tutorial (Part 2)
Introduction to Go
Go is designed for simplicity, efficiency, and scalability. Its features make it ideal for microservices,
networking tools, and cloud-native applications.
1. Setting Up Go
1. Install Go
Download and install from [Link]/dl.
2. Verify Installation
bash
Copy code
go version
3. Setup Workspace
• By default, Go uses ~/go for its workspace.
• Ensure GOPATH and GOROOT are correctly set.
2. Create a Basic Go Application
Hello World
1. Create a file named [Link]:
go
Copy code
package main
import "fmt"
func main() {
[Link]("Hello, World!")
}
2. Run it:
bash
Copy code
go run [Link]
3. Build an executable:
bash
Copy code
go build [Link]
./main
3. Key Features of Go
Simple Variable Declaration
go
Copy code
package main
import "fmt"
func main() {
var name string = "Go"
version := 1.19 // Short syntax
[Link](name, "version:", version)
}
Functions with Multiple Returns
go
Copy code
package main
import "fmt"
func divide(a, b int) (int, int) {
return a / b, a % b
}
func main() {
quotient, remainder := divide(10, 3)
[Link]("Quotient:", quotient, "Remainder:", remainder)
}
Loops
Go uses only the for loop:
go
Copy code
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
[Link]("Iteration:", i)
}
}
4. Working with Collections
Arrays and Slices
go
Copy code
package main
import "fmt"
func main() {
// Arrays
var arr = [3]int{1, 2, 3}
[Link]("Array:", arr)
// Slices
slice := []int{10, 20, 30}
slice = append(slice, 40)
[Link]("Slice:", slice)
}
Maps (Dictionaries)
go
Copy code
package main
import "fmt"
func main() {
user := map[string]string{"name": "John", "role": "admin"}
[Link]("User:", user["name"])
}
5. Structs and Methods
Structs
go
Copy code
package main
import "fmt"
type Car struct {
Brand string
Year int
}
func main() {
car := Car{Brand: "Toyota", Year: 2020}
[Link](car)
}
Methods
go
Copy code
func (c Car) Display() {
[Link]("Brand: %s, Year: %d\n", [Link], [Link])
}
6. Concurrency with Goroutines
Goroutines
Goroutines are lightweight threads:
go
Copy code
package main
import (
"fmt"
"time"
)
func say(message string) {
for i := 0; i < 5; i++ {
[Link](message)
[Link](100 * [Link])
}
}
func main() {
go say("Hello")
say("World")
}
Channels
Channels enable communication between Goroutines:
go
Copy code
package main
import "fmt"
func sum(a int, b int, ch chan int) {
ch <- a + b // Send data to channel
}
func main() {
ch := make(chan int)
go sum(3, 4, ch)
result := <-ch // Receive data from channel
[Link]("Sum:", result)
}
7. Error Handling
Using error Interface
go
Copy code
package main
import (
"errors"
"fmt"
)
func checkAge(age int) error {
if age < 18 {
return [Link]("age must be 18 or older")
}
return nil
}
func main() {
err := checkAge(16)
if err != nil {
[Link]("Error:", err)
} else {
[Link]("Access granted")
}
}
8. File Handling
Reading Files
go
Copy code
package main
import (
"fmt"
"os"
)
func main() {
data, err := [Link]("[Link]")
if err != nil {
[Link]("Error:", err)
}
[Link](string(data))
}
Writing to Files
go
Copy code
package main
import (
"fmt"
"os"
)
func main() {
err := [Link]("[Link]", []byte("Hello, Go!"), 0644)
if err != nil {
[Link]("Error:", err)
}
}
9. Web Servers in Go
Basic HTTP Server
go
Copy code
package main
import (
"fmt"
"net/http"
)
func handler(w [Link], r *[Link]) {
[Link](w, "Welcome to Go Web Server!")
}
func main() {
[Link]("/", handler)
[Link](":8080", nil)
}
10. Testing
Basic Test
go
Copy code
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 {
[Link]("Expected 5, got %d", result)
}
}
Run the tests:
bash
Copy code
go test
11. Modules and Dependencies
Initialize a Module
bash
Copy code
go mod init [Link]/myproject
Install Dependencies
bash
Copy code
go get [Link]/gorilla/mux
Use the package in your project:
go
Copy code
package main
import (
"fmt"
"[Link]/gorilla/mux"
)
func main() {
r := [Link]()
[Link]("Router created:", r)
}
This tutorial covers practical aspects of Go. With these basics, you can start building robust and
scalable applications. For deeper insights, explore topics like interfaces, reflection, and advanced
concurrency patterns.