rust学习——变量遮蔽特性(继承式可变)

遮蔽

声明和前面变量具有相同名称的新变量

例子1

fn main() {
    let x = 5;

    let x = x + 1;

    {
        let x = x * 2;
        println!("The value of x in the inner scope is: {}", x);
    }

    println!("The value of x is: {}", x);
}

运行

$ cargo run
   Compiling variables v0.1.0 (file:///projects/variables)
    Finished dev [unoptimized + debuginfo] target(s) in 0.31s
     Running `target/debug/variables`
The value of x in the inner scope is: 12
The value of x is: 6

例子2

let c = Context::new();
let c = c.rot_deg(90.0);
let transform = c.transform;

let c = Context::new();
let c = c.scale(2.0, 3.0); 
let transform = c.transform;

上面代码用同一个变量 c,持有上下文,利用变量遮蔽,调用不同的方法,返回不同的类型,在代码维护可读性上是非常有帮助的。(别说人的,不是我说的。)

你可能感兴趣的:(rust从入门到放弃,rust,学习,java)