typepersonstruct { name string age int}func (p person) display() { fmt.Println(p.name, p.age)}funcdefer_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)}funcmain() {defer_test()}/*Let me intro to u:and after onr year his age: 37Leborn James 36*/
packagemainimport ( "fmt")funcprintA(a int) { fmt.Println("value of a in deferred function", a)}funcmain() { a :=5deferprintA(a) a =10 fmt.Println("value of a before deferred function call", a)}// value of a in deferred function 5 //
packagemain/*Pratical usage cases of the defer statement */import ("fmt""sync")typerectstruct { 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)}funcmain() { r1 :=rect{12.0, -9.2} r2 :=rect{11.2, 2} r3 :=rect{11., -90.} rects := []rect{r1, r2, r3}var wg sync.WaitGroupfor _, 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 positiveThe width of rect must be positiveThe area of rect: 22.4All the routine finished*/