0% found this document useful (0 votes)
10 views

Go Programming Language Tutorial (Part 2)

A Go Programming Language Tutorial (Part 2)

Uploaded by

eowug
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Go Programming Language Tutorial (Part 2)

A Go Programming Language Tutorial (Part 2)

Uploaded by

eowug
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

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 golang.org/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 main.go:
go
Copy code
package main

import "fmt"

func main() {
fmt.Println("Hello, World!")
}

2. Run it:
bash
Copy code
go run main.go

3. Build an executable:
bash
Copy code
go build main.go
./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
fmt.Println(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)
fmt.Println("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++ {
fmt.Println("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}
fmt.Println("Array:", arr)

// Slices
slice := []int{10, 20, 30}
slice = append(slice, 40)
fmt.Println("Slice:", slice)
}

Maps (Dictionaries)
go
Copy code
package main

import "fmt"

func main() {
user := map[string]string{"name": "John", "role": "admin"}
fmt.Println("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}
fmt.Println(car)
}

Methods
go
Copy code
func (c Car) Display() {
fmt.Printf("Brand: %s, Year: %d\n", c.Brand, c.Year)
}

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++ {
fmt.Println(message)
time.Sleep(100 * time.Millisecond)
}
}

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
fmt.Println("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 errors.New("age must be 18 or older")
}
return nil
}

func main() {
err := checkAge(16)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Access granted")
}
}

8. File Handling
Reading Files
go
Copy code
package main

import (
"fmt"
"os"
)

func main() {
data, err := os.ReadFile("test.txt")
if err != nil {
fmt.Println("Error:", err)
}
fmt.Println(string(data))
}

Writing to Files
go
Copy code
package main

import (
"fmt"
"os"
)

func main() {
err := os.WriteFile("output.txt", []byte("Hello, Go!"), 0644)
if err != nil {
fmt.Println("Error:", err)
}
}

9. Web Servers in Go
Basic HTTP Server
go
Copy code
package main

import (
"fmt"
"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {


fmt.Fprintf(w, "Welcome to Go Web Server!")
}

func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":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 {
t.Errorf("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 example.com/myproject

Install Dependencies
bash
Copy code
go get github.com/gorilla/mux

Use the package in your project:


go
Copy code
package main

import (
"fmt"
"github.com/gorilla/mux"
)

func main() {
r := mux.NewRouter()
fmt.Println("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.

You might also like