Go Language Tutorial
What is Go Language?
Go, also known as Golang, is an open-source programming language created by Google. It is designed to be simple, efficient, and reliable, making it an ideal choice for building scalable and high-performance applications.
Installation
Windows
- Download the installer from the official Go website.
- Run the installer and follow the instructions.
- Verify the installation by opening a command prompt and typing
go version
.
macOS
- Download the package from the official Go website.
- Open the package and follow the instructions.
- Verify the installation by opening a terminal and typing
go version
.
Linux
- Download the tarball from the official Go website.
- Extract the tarball and move it to
/usr/local
: - Add Go to your PATH by adding the following line to your
~/.profile
or~/.bashrc
file: - Reload your profile by running
source ~/.profile
orsource ~/.bashrc
. - Verify the installation by opening a terminal and typing
go version
.
tar -C /usr/local -xzf go1.16.5.linux-amd64.tar.gz
export PATH=$PATH:/usr/local/go/bin
Where is Go Useful?
Go is particularly useful for:
- Web Development: Building fast and scalable web applications.
- Cloud Services: Developing cloud-native applications and microservices.
- Networking Tools: Creating efficient networked servers and clients.
- Data Processing: Handling large volumes of data with high performance.
- System Programming: Writing low-level system utilities and tools.
Tutorial with Examples
Hello, World!
Let's start with a simple "Hello, World!" program in Go:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Basic Data Types
Go supports several basic data types including integers, floats, strings, and booleans. Here's an example:
package main
import "fmt"
func main() {
var a int = 10
var b float64 = 3.14
var c string = "Hello"
var d bool = true
fmt.Println(a, b, c, d)
}
Control Structures
Go provides common control structures such as if-else statements, loops, and switch cases. Here's an example using a for loop:
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Println(i)
}
}
Functions
Functions in Go are first-class citizens and can be passed as arguments, returned from other functions, and assigned to variables. Here's a simple function example:
package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func main() {
result := add(2, 3)
fmt.Println(result)
}
Structs
Structs are used to create custom data types. Here's an example of defining and using a struct:
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
person := Person{Name: "Alice", Age: 30}
fmt.Println(person)
}
Slices
Slices are dynamically-sized arrays. Here's an example of creating and using slices:
package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4, 5}
fmt.Println(numbers)
}
Maps
Maps are key-value pairs. Here's an example of creating and using maps:
package main
import "fmt"
func main() {
m := map[string]int{"Alice": 30, "Bob": 25}
fmt.Println(m)
}
Concurrency
Go has built-in support for concurrent programming. Here's an example using goroutines and channels:
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
}
Error Handling
Go uses error values to handle errors. Here's an example of basic error handling:
package main
import (
"errors"
"fmt"
)
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("cannot divide 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)
}
}
Code to Process 1 million messages in parallel and benchmark the performance
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
// Sample message struct
type Message struct {
ID int
Content string
}
// Function to process a message
func processMessage(msg Message) {
// Simulate processing time
time.Sleep(time.Millisecond)
}
// Function to generate 1 million sample messages
func generateMessages(numMessages int) []Message {
messages := make([]Message, numMessages)
for i := 0; i < numMessages; i++ {
messages[i] = Message{
ID: i,
Content: fmt.Sprintf("Message content %d", rand.Int()),
}
}
return messages
}
func main() {
// Number of messages to process
const numMessages = 1000000
// Generate sample messages
messages := generateMessages(numMessages)
// Benchmark start time
start := time.Now()
// Use a WaitGroup to wait for all goroutines to finish
var wg sync.WaitGroup
wg.Add(numMessages)
// Channel to limit the number of concurrent goroutines
const maxGoroutines = 1000
guard := make(chan struct{}, maxGoroutines)
for _, msg := range messages {
// Add a struct to the channel to limit the concurrency
guard <- struct{}{}
// Launch a goroutine to process each message
go func(msg Message) {
defer wg.Done()
processMessage(msg)
<-guard // Remove a struct from the channel after processing
}(msg)
}
// Wait for all goroutines to finish
wg.Wait()
// Benchmark end time
duration := time.Since(start)
fmt.Printf("Processed %d messages in %v\n", numMessages, duration)
}
No comments:
Post a Comment