Go defer Statement: Understanding and Usage
In Go, 'defer' is a statement that schedules a function call to be executed after the surrounding function returns. The 'defer' statement is often used to ensure that resources are released, like closing a file or releasing a mutex, regardless of whether the function completes successfully or not.
For example:
func exampleFunc() {
defer fmt.Println('This will be printed last')
fmt.Println('This will be printed first')
}
In the above code, the function 'exampleFunc()' prints two lines of text. However, the 'defer' statement ensures that the 'fmt.Println('This will be printed last')' statement is executed after the function has completed, and thus it will be printed last.
Multiple 'defer' statements can be used in a function, and they will be executed in the reverse order that they were defined.
func exampleFunc() {
defer fmt.Println('This will be printed last')
defer fmt.Println('This will be printed second to last')
fmt.Println('This will be printed first')
}
In this case, the output will be:
This will be printed first
This will be printed second to last
This will be printed last
原文地址: https://www.cveoy.top/t/topic/nlWm 著作权归作者所有。请勿转载和采集!