欢迎来到 AI 中文社区(简称 AI 中文社),这里是学习交流 AI 人工智能技术的中文社区。 为了更好的体验,本站推荐使用 Chrome 浏览器。
Move语言 作用域
Move 语言的作用域是指绑定生效的代码区域。换句话说,变量存在于作用域中。
Move 语言的作用域是由花括号扩起来的代码块,它本质上是一个块。
定义一个代码块,实际上是定义一个作用域。
script {
fun scope_sample() {
// this is a function scope
{
// this is a block scope inside function scope
{
// and this is a scope inside scope
// inside functions scope... etc
};
};
{
// this is another block inside function scope
};
}
}
从该示例可以看出,作用域是由代码块(或函数)定义的。它们可以嵌套,并且可以定义多个作用域,数量没有限制。
变量的生命周期和可见性
我们前面已经介绍过关键字 let 的作用,它可以用来定义变量。有一点需要强调的是,该变量仅存在于变量所处的作用域内。
也就是说,它在作用域之外不可访问,并在作用域结束后立即消亡。
script {
fun let_scope_sample() {
let a = 1; // we've defined variable A inside function scope
{
let b = 2; // variable B is inside block scope
{
// variables A and B are accessible inside
// nested scopes
let c = a + b;
}; // in here C dies
// we can't write this line
// let d = c + b;
// as variable C died with its scope
// but we can define another C
let c = b - 1;
}; // variable C dies, so does C
// this is impossible
// let d = b + c;
// we can define any variables we want
// no name reservation happened
let b = a + 1;
let c = b + 1;
} // function scope ended - a, b and c are dropped and no longer accessible
}
变量仅存在于其作用域(或代码块)内,当作用域结束时变量随之消亡。
下一章:Move语言 常量
Move 支持模块或脚本级常量。常量一旦定义,就无法更改,所以可以使用常量为特定模块或脚本定义一些不变量,例如角色、标识符等。常量可以定义为基本类型(比如整数,布尔值和地址),也可以定义为数组。我们可以通过名称访问常量, ...
AI 中文社