Rust 变量绑定
来源:互联网 发布:linux 破解root密码 编辑:程序博客网 时间:2024/06/06 20:59
变量绑定是指将一些值绑定到一个名字上,这样可以在之后使用他们。Rust 中使用 let 声明一个绑定:
fn main() { let x = 123;}
可变
绑定默认是不可变的(immutable)。下面的代码将不能编译:
let x = 123;x = 456;
编译器会给出如下错误:
Compiling hello_world v0.1.0 (yourpath/hello_world)error[E0384]: re-assignment of immutable variable `x` --> main.rs:3:5 |2 | let x = 123; | - first assignment to `x`3 | x = 456; | ^^^^^^^ re-assignment of immutable variable
如果想使得绑定是可变的,使用 mut:
let mut x = 123;x = 456;
如果你声明了一个可变绑定而又没有改变它,虽然可以编译通过,但编译器还是会给出一些建议和警告:
let mut x = 123; Compiling hello_world v0.1.0 (yourpath/hello_world)warning: unused variable: `x`, #[warn(unused_variables)] on by default --> main.rs:2:9 |2 | let mut x = 123; | ^^^^^warning: variable does not need to be mutable, #[warn(unused_mut)] on by default --> main.rs:2:9 |2 | let mut x = 123; | ^^^^^ Finished debug [unoptimized + debuginfo] target(s) in 0.63 secs
这正是 Rust 出于安全的目的。
初始化绑定
Rust 变量绑定有另一个不同于其他语言的方面:绑定要求在可以使用它之前必须初始化。
例如以下代码:
fn main() { let x: i32; println!("Hello world!");}
Rust 会警告我们从未使用过这个变量绑定,但是因为我们从未用过它,无害不罚。
Compiling hello_world v0.1.0 (yourpath/hello_world)warning: unused variable: `x`, #[warn(unused_variables)] on by default --> main.rs:2:9 |2 | let x: i32; | ^ Finished debug [unoptimized + debuginfo] target(s) in 0.29 secs
然而,如果确实想使用 x, 事情就不一样了。修改代码:
fn main() { let x: i32; println!("The value of x is: {}", x);}
这是无法通过编译的:
Compiling hello_world v0.1.0 (yourpath/hello_world)error[E0381]: use of possibly uninitialized variable: `x` --> main.rs:3:39 |3 | println!("The value of x is: {}", x); | ^ use of possibly uninitialized `x`<std macros>:2:27: 2:58 note: in this expansion of format_args!<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)main.rs:3:5: 3:42 note: in this expansion of println! (defined in <std macros>)error: aborting due to previous errorerror: Could not compile `hello_world`.
Rust 不允许我们使用一个未经初始化的绑定。
Mode
在许多语言中,这叫做变量。不过 Rust 的变量绑定有一些不同的巧妙之处。例如 let语句的左侧是一个“模式”,而不仅仅是一个变量。我们也可以这样写:
let (x, y) = (1, 2);
在这个语句被计算后,x 将会是1,’y’ 将会是2。也许有人会忍不住说:这不类似于 golang 中的多变量绑定嘛。
var x, y = 1, 2
事实上不是这样的。(1, 2)这种形式是一个元组,是一个固定大小的有序列表。上面的例子还可以写成以下形式:
let n = (1, "hello");let (x, y) = n;
第一个let将一个元组(1, “hello”)绑定到n上,第二个let将元组解构,将元组中的字段绑定到x和y上。
更多模式和元组(Tuple)的特性,将在后续的章节详细介绍。
类型注解
Rust 是一个静态类型语言,意味着我们需要先确定我们需要的类型。事实上,Rust 有一个叫做类型推断的功能,如果它能确认这是什么类型,就不需要明确指定类型。当然也可以显示的标注类型, 类型写在一个冒号’:’后面:
let x: i32 = 123;
对于数值类型,也可以这样:
let x = 123i32; // let x: i32 = 123let y = 123_i32; // let y: i32 = 123let z = 100_000i32; // let z: i32 = 100000
- Rust 变量绑定
- Rust语法之变量绑定
- 边做边学Rust之变量绑定
- Rust之语法<1>变量绑定
- Rust 变量
- rust:打印变量地址
- Rust 变量与函数
- rust 变量基础
- Rust 中的变量和赋值
- rust
- 绑定变量!
- 绑定变量
- 绑定变量
- 绑定变量
- 绑定变量
- 绑定变量
- 绑定变量
- 绑定变量
- JAXB实现XML和java对象互转以及soapXml和对象互转需要注意的地方
- WinForm控件基础--菜单类控件
- 关于爬虫爬取图片被防盗链的解决
- Rust使用Cargo
- js判断是微信、QQ内置浏览器打开页面
- Rust 变量绑定
- Rust 函数
- AsyncQueryHandler代码分析
- IntentService解析及使用规范
- Update Strategy小记
- Rust 数据类型
- 使用ssh公钥实现免密码登录
- 支付网关接入中的ssl连接和签名调试tips
- Rust 运算符