Introduction
Practical use cases show how to use Go in real life to solve common problems simply and clearly.
// Go programs start with package main package main import "fmt" func main() { // Your code here fmt.Println("Hello, world!") }
package main import "fmt" func main() { fmt.Println("Print a message") }
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") }
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) }
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) } }
net/http package provides tools to create web servers in Go.http.ListenAndServe starts a server listening on a specified port.net/http package with http.ListenAndServe -> Option Anet/http.ListenAndServe [OK]os.Open opens a file in read-only mode and returns a file and error.file, err := os.Open("data.txt") correctly assigns both file and error.package main
import "fmt"
func main() {
nums := []int{2, 4, 6}
squares := make(map[int]int)
for _, n := range nums {
squares[n] = n * n
}
fmt.Println(squares)
}package main
import (
"fmt"
"os"
)
func main() {
file := os.Open("file.txt")
defer file.Close()
fmt.Println("File opened")
}os.Open returns two values: file and error. The code only assigns one variable.os.Open opens the file for reading; then you can scan or read lines.os.Create to create output file and WriteString or similar to write results.os.Open to read, loop to square, and os.Create with WriteString to save -> Option DPass the test and this pattern moves unknown