Skip to content

Block Scope

IsaacShelton edited this page Mar 21, 2022 · 1 revision

Block Scope

Block scopes are a type of scope that exists inside of a function scope

Example

Every HERE represents where a block scope exists

func myExampleFunction {
    if my_condition {
        HERE
    }
    if my_condition, HERE
    if my_condition HERE
    if(my_condition) HERE
    
    // same rules apply to other types of conditionals
}

Caution

A common mistake is to not take into account values that use ownership-based memory management inside of block scopes.

For example

import basics

func main {
    name String
    
    if true {
        user_input String = scan("Enter your name: ")
        
        name = user_input // BAD!!!
    }
    
    print(name)
}

will crash, since user_input is destroyed by the time we are trying to use the string view name which references user_input.

This can easily be fixed by transferring ownership from user_input to name, so that the string data will outlive the scope of user_input. For String, we can use the commit method.

import basics

func main {
    name String
    
    if true {
        user_input String = scan("Enter your name: ")
        
        name = user_input.commit() // GOOD
    }
    
    print(name)
}

For more in-depth information about String scoping specifically, see String

Clone this wiki locally