Go (Golang) Advanced Programming
Lab
Lab Manual: 10 Advanced Level Programs
Contents:
1. Goroutines Example
2. Channel Communication
3. Structs and Methods
4. Interfaces Example
5. Select Statement
6. Map Example
7. File Writing
8. File Reading
9. HTTP Server
10. Defer Statement
Goroutines Example
Code:
package main
import (
"fmt"
"time"
)
func printNumbers() {
for i := 1; i <= 5; i++ {
fmt.Println(i)
time.Sleep(500 * time.Millisecond)
}
}
func main() {
go printNumbers()
time.Sleep(3 * time.Second)
fmt.Println("Main function finished")
}
Output:
1
2
3
4
5
Main function finished
Channel Communication
Code:
package main
import "fmt"
func main() {
messages := make(chan string)
go func() { messages <- "ping" }()
msg := <-messages
fmt.Println(msg)
}
Output:
ping
Structs and Methods
Code:
package main
import "fmt"
type Person struct {
name string
age int
}
func (p Person) greet() {
fmt.Printf("Hello, my name is %s\n", p.name)
}
func main() {
p := Person{name: "John", age: 30}
p.greet()
}
Output:
Hello, my name is John
Interfaces Example
Code:
package main
import "fmt"
type Shape interface {
area() float64
}
type Circle struct {
radius float64
}
func (c Circle) area() float64 {
return 3.14 * c.radius * c.radius
}
func main() {
var s Shape = Circle{5}
fmt.Println("Area:", s.area())
}
Output:
Area: 78.5
Select Statement
Code:
package main
import (
"fmt"
"time"
)
func main() {
c1 := make(chan string)
c2 := make(chan string)
go func() {
time.Sleep(1 * time.Second)
c1 <- "one"
}()
go func() {
time.Sleep(2 * time.Second)
c2 <- "two"
}()
for i := 0; i < 2; i++ {
select {
case msg1 := <-c1:
fmt.Println("received", msg1)
case msg2 := <-c2:
fmt.Println("received", msg2)
}
}
}
Output:
received one
received two
Map Example
Code:
package main
import "fmt"
func main() {
m := map[string]int{"a": 1, "b": 2}
m["c"] = 3
fmt.Println(m)
}
Output:
map[a:1 b:2 c:3]
File Writing
Code:
package main
import (
"os"
)
func main() {
f, _ := os.Create("test.txt")
defer f.Close()
f.WriteString("Hello, File!")
}
Output:
Writes 'Hello, File!' to test.txt
File Reading
Code:
package main
import (
"fmt"
"os"
)
func main() {
data, _ := os.ReadFile("test.txt")
fmt.Println(string(data))
}
Output:
Hello, File!
HTTP Server
Code:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Welcome to Go Web Server")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
Output:
Runs server at localhost:8080
Defer Statement
Code:
package main
import "fmt"
func main() {
defer fmt.Println("world")
fmt.Println("hello")
}
Output:
hello
world