可变接收器及纯函数(Mutable receivers & pure functions)


struct User {
    is_registered bool
}

fn (u mut User) register() {
    u.is_registered = true
}

fn main() {
    mut user := User{}
    println(user.is_registered) // ==> "false"  
    user.register()
    // TODO: Maybe force marking methods that modify the receiver with `!`
    // user.register()!  
    println(user.is_registered) // ==> "true"  
}

请注意,功能只能修改接收器。fn register(u mut User)这样的做法无法通过编译。

这点非常重要,所以再次申明:V语言中函数是部分纯的,它们的参数永远不会被函数修改。

修改对象的另一种方法是返回修改后的版本(*待实现):

// TODO: this syntax is not implemented yet  
fn register(u User) User {
    return { u | is_registered: true }
}

user = register(user)

results matching ""

    No results matching ""