In Rust, you bind values to a variable name using the let
keyword. This is often referred to as “variable binding” because it’s like binding a name to a value.
Here’s a simple example:
let x = 5;
In this example, x
is bound to the value 5
. By default, bindings are immutable in Rust. If you try to reassign x
to a different value, you’ll get a compile-time error. If you want a binding to be mutable, you can use the mut
keyword:
let mut x = 5;
x = 10; // This is okay because x is mutable
In Rust, you can also bind a variable to an expression. The expression will be evaluated, and the resulting value will be bound to the variable:
let x = 5 * 5; // x is bound to the value 25
Variable binding in Rust also allows for pattern matching, which enables more complex types of binding. For example, if you have a tuple, you can bind the individual elements of the tuple to different variables:
let (x, y) = (1, 2); // x is bound to 1, and y is bound to 2
Rust also requires that all variables be initialized before they are used, which prevents undefined behavior.
Lastly, Rust features a system of “shadowing” where a new variable can be declared with the name of a previous variable, effectively creating a new variable that “shadows” the old one.文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-621212.html
let x = 5;
let x = x + 5; // x is now 10
let x = x * 2; // x is now 20
Each x
is a new variable that shadows the previous x
. This is not the same as mutation because these x
s are new variables, they just happen to have the same name as the previous variable.文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-621212.html
fn main() {
/*
變量是有作用域的,也就是在一個(gè)代碼塊中生存。
代碼塊 {}, 也允許變量遮蔽。
*/
// main 函數(shù)中
let spend = 1;
{
// 只存在本代碼塊中
let target = "面向?qū)ο?;
println!("內(nèi)部 {}", target); // 內(nèi)部 面向?qū)ο?/span>
// 遮蔽了外面的spend
let spend = 2.0;
println!("內(nèi)部 {}", spend); // 內(nèi)部 2
}
// target在此作用域是不存在的
// println!("外部 {}", target);
println!("外部 {}", spend); // 外部 1
// 遮蔽了spend
let spend = String::from("學(xué)習(xí)時(shí)間1小時(shí)");
println!("外部 {}", spend); // 外部 學(xué)習(xí)時(shí)間1小時(shí)
let spend2;
{
let x = 2;
spend2 = x * x;
}
println!("spend2: {}", spend2); // spend2: 4
let spend3;
// println!("spend3: {}", spend3); // 報(bào)錯(cuò),使用了未初始化的綁定
spend3 = 1;
println!("another binding spend3: {}", spend3); // another binding spend3: 1
// 凍結(jié) 資源存在使用的引用時(shí),在當(dāng)前作用域中這一資源是不可被修改的。
let mut spend4 = Box::new(1);
let spend5 = &spend4; // `spend4` is borrowed here
spend4 = Box::new(100); // `spend4` is assigned to here but it was already borrowed
println!("{}", spend4);
println!("{}", spend5);
}
到了這里,關(guān)于Rust- 變量綁定的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!