Sobes.tech
Junior — Senior

Deferred call defer: differences between passing values and pointers

livecode

Task condition

It is necessary to understand what data the program will output if using the defer statement for functions that accept both regular values and pointers.

func main() {
    fmt.Println(test1())
    test3()
}

func test3() {
    var a int = 10
    var b = 20
    var ptr *int = &b

    defer printInt("a", a)
    defer printInt("ptr as value", *ptr)
    defer printIntPointer("ptr as pointer", ptr)

    a = 1010
    *ptr = 2020
}

func changeI(i *int) {
    *i = 10
}

func printInt(label string, v int) {
    fmt.Printf("%s=%d\n", label, v)
}

func printIntPointer(label string, p *int) {
    fmt.Printf("%s=%d\n", label, *p)
}