Certainly! More examples will help you grasp the key concepts. Here's the expanded learning plan with examples.
go versionDeclare different types of variables.
var x int = 10
y := 20
var z float64 = 3.14Examples of if, for, and switch.
// If-Else
if x > y {
fmt.Println("x is greater")
} else {
fmt.Println("y is greater")
}
// For loop
for i := 0; i < 10; i++ {
fmt.Println(i)
}
// Switch
switch x {
case 10:
fmt.Println("Ten")
default:
fmt.Println("Not Ten")
}Declaring and calling a function.
func add(a int, b int) int {
return a + b
}Arrays, slices, and maps.
// Array
var arr [5]int = [5]int{1, 2, 3, 4, 5}
// Slice
slice := []int{1, 2, 3}
// Map
m := map[string]int{"Apple": 1, "Orange": 2}func greet(name string) string {
return "Hello " + name
}Example of importing a custom package.
Create a file math.go:
package math
func Add(a int, b int) int {
return a + b
}Import and use it:
import "path/to/math"
result := math.Add(1, 2)Simple HTTP server with a handler.
func helloWorld(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, world!")
}Installation and basic routing example.
go get -u github.com/gorilla/muxExample:
r := mux.NewRouter()
r.HandleFunc("/", helloWorld)How to handle GET and POST requests.
r.HandleFunc("/users", getUsers).Methods("GET")
r.HandleFunc("/users", createUser).Methods("POST")Install PostgreSQL driver and connect.
go get -u github.com/lib/pqconnStr := "user=username dbname=mydb sslmode=disable"
db, err := sql.Open("postgres", connStr)This is quite a lot to cover in one day, but it should give you a strong foundation in Go backend development. I've included resources to delve deeper into each topic.