type person struct {
name string
age int
}
func (p person) display() {
fmt.Println(p.name, p.age)
}
func defer_test() {
p := person{"Leborn James", 36}
defer p.display()
p.age += 1
fmt.Println("Let me intro to u:")
fmt.Println("and after onr year his age:", p.age)
}
func main() {
defer_test()
}
/*Let me intro to u:
and after onr year his age: 37
Leborn James 36
*/
package main
import (
"fmt"
)
func printA(a int) {
fmt.Println("value of a in deferred function", a)
}
func main() {
a := 5
defer printA(a)
a = 10
fmt.Println("value of a before deferred function call", a)
}
// value of a in deferred function 5
//
package main
/*Pratical usage cases of the defer statement */
import (
"fmt"
"sync"
)
type rect struct {
length, width float64
}
func (r rect) area(wg *sync.WaitGroup) {
defer wg.Done()
if r.width <= 0 {
fmt.Println("The width of rect must be positive")
return
}
if r.length <= 0 {
fmt.Println("The length of rect must be positive")
return
}
area := r.length * r.width
fmt.Println("The area of rect:", area)
}
func main() {
r1 := rect{12.0, -9.2}
r2 := rect{11.2, 2}
r3 := rect{11., -90.}
rects := []rect{r1, r2, r3}
var wg sync.WaitGroup
for _, item := range rects {
wg.Add(1)
go item.area(&wg)
}
wg.Wait()
fm
t.Println("All the routine finished")
}
/*The width of rect must be positive
The width of rect must be positive
The area of rect: 22.4
All the routine finished
*/