You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
IsaacShelton edited this page Mar 21, 2022
·
1 revision
Defer
Defer statements are used to postpone a statement until the end of the current scope
import basics
func main {
defer print("One")
defer print("Two")
defer print("Three")
print("I will be printed before anything else")
}
I will be printed before anything else
Three
Two
One
When the end of the scope is reached, or the scope is going to be left, all deferred statements will be executed in the reverse order they were encountered.
Common Uses
The most common use of defer is to free dynamically allocated memory
import basics
func main {
x_squared_integers *int = new int * 10
defer delete x_squared_integers
// 0, 1, 4, 9, 16, etc.
repeat 10, x_squared_integers[idx] = idx * idx
// Print each
repeat 10, print(x_squared_integers[idx])
}