Skip to content

defer outside a function #186

@kofj

Description

@kofj
import (
    "fmt"
    "time"
)

func calc(index string, a, b int) int {
     time.Sleep(1e9)
    ret := a + b
    fmt.Println(time.Now().Unix(),"\t",index,"\t", a, "\t", b, "\t", ret)
    return ret
}

// func main() {
    a := 1
    b := 2
//     defer calc("1", a, 3)
    defer calc("1", a, calc("10", a, b))

    a = 0
//     defer calc("2", a, 2)
    defer calc("2", a, calc("20", a, b))
    b = 1
// }

// log.Println("\n\n")

WANT

1572422679 	 10 	 1 	 2 	 3
1572422680 	 20 	 0 	 2 	 2
1572422681 	 2 	 0 	 2 	 2
1572422682 	 1 	 1 	 3 	 4

But, got:

1572423309 	 10 	 1 	 2 	 3
1572423310 	 1 	 1 	 3 	 4
1572423311 	 20 	 0 	 2 	 2
1572423312 	 2 	 0 	 2 	 2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions