0
0
Goprogramming~7 mins

Practical use cases in Go

Choose your learning style9 modes available
Introduction
Practical use cases show how to use Go in real life to solve common problems simply and clearly.
When you want to build a simple web server to share information.
When you need to read and write files on your computer.
When you want to process data like numbers or text quickly.
When you want to create a small program that talks to a database.
When you want to make a tool that runs commands automatically.
Syntax
Go
// Go programs start with package main
package main

import "fmt"

func main() {
    // Your code here
    fmt.Println("Hello, world!")
}
Every Go program starts with package main and a main function.
Use import to include extra tools like fmt for printing.
Examples
Prints a simple message to the screen.
Go
package main

import "fmt"

func main() {
    fmt.Println("Print a message")
}
Creates a file and writes text into it.
Go
package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := os.Create("test.txt")
    if err != nil {
        fmt.Println("Error creating file")
        return
    }
    defer file.Close()
    file.WriteString("Hello file")
    fmt.Println("File written")
}
Defines a function to add two numbers and prints the result.
Go
package main

import "fmt"

func add(a int, b int) int {
    return a + b
}

func main() {
    sum := add(3, 4)
    fmt.Println("Sum is", sum)
}
Sample Program
This program starts a simple web server on your computer. When you open http://localhost:8080 in a browser, it shows 'Hello, visitor!'.
Go
package main

import (
    "fmt"
    "net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello, visitor!")
}

func main() {
    http.HandleFunc("/", helloHandler)
    fmt.Println("Starting server at :8080")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println("Server error:", err)
    }
}
OutputSuccess
Important Notes
Go is great for building fast and simple tools.
You can combine small programs like these to make bigger projects.
Always check for errors when working with files or network.
Summary
Practical use cases help you see how Go works in real life.
You can build web servers, work with files, and do math easily.
Start small and build your skills step by step.