warning: unused variable: `a`
--> src/main.rs:2:9
|
2 | let a = 4;
| ^ help: if this is intentional, prefix it with an underscore: `_a`
|
= note: `#[warn(unused_variables)]` on by default
warning: `demo` (bin "demo") generated 1 warning
变量遮盖,shadowing。
fn main() {
let a = 5;
let a = 6;
println!("{}", a)
}
warning: unused variable: `a`
--> src/main.rs:2:9
|
2 | let a = 5;
| ^ help: if this is intentional, prefix it with an underscore: `_a`
|
= note: `#[warn(unused_variables)]` on by default
warning: `demo` (bin "demo") generated 1 warning
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.97s
Running `target/debug/demo`
6
fn main() {
let a = 0.1;
let b = 0.2;
let c: f64 = 0.3;
let is_eq = a + b == c;
println!("is_eq = {}", is_eq);
// 若a或b或c不指定为f64则panic,因为assert不能分辨计算后的类型
let is_eq = (c - a - b).abs() < 0.0001;
println!("is_eq = {}", is_eq);
}
is_eq = false
is_eq = true
序列循环
fn main() {
for i in 1..4 {
print!("{}", i);
}
println!("");
for i in 1..=4 {
print!("{}", i);
}
// 如果此局部变量在本块中并不会用到,可以简单使用—个下画线来代替此变量
for _ in 0..3 {
println!("hello")
}
// 不推荐使用这种方式,因为会带来额外的运行时边界检查
let connections = [0, 1, 2, 3, 4, 5];
for i in 0..connections.len() {
println!("{}", connections[i])
}
// loop 可以作为无限循环使用,break可打断。
// 跳转标签
'outter: for i in 0.. {
for j in 0.. {
for k in 0.. {
if i + j + k % 100 == 0 {
break 'outter;
}
}
}
}
println!("outter break");
// 从循环中获取一个返回值
let a = loop {
break 123;
};
}
数组
分为静态数组和可变数组。
fn main() {
// 为固定尺⼨的数据类型是可以直接放栈上的,创建和回收都⽐在堆上动态分配的动态数组性能要好
let arr:[i64; 4] = [1, 2, 3, 4];
println!("arr {:?}", arr);
let arr = [1, 2, 3, 4];
println!("arr {:?}", arr);
for (count, elem) in arr.iter().enumerate() {
println!("index :{}: value {}", count, elem);
}
for elem in arr {
println!("elem {}", elem);
}
for i in 0..arr.len() {
println!("arr[{}] {}", i, arr[i]);
}
let mut dynamic_arr: Vec<i32> = Vec::new();
dynamic_arr.push(1);
println!("dynamic_arr {:?}", dynamic_arr);
let dynamic_arr = vec![1, 2, 3, 4];
println!("dynamic_arr {:?}", dynamic_arr);
for (count, elem) in dynamic_arr.iter().enumerate() {
println!("index :{}: value {}", count, elem);
}
// 注意 若是 elem in dynamic_arr 这种形式,则后续的for则无法编译过,因为这种形式所有权发生了变化。
for elem in &dynamic_arr {
println!("elem {}", elem);
}
for i in 0..dynamic_arr.len() {
println!("arr[{}] {}", i, arr[i]);
}
}
// arr [1, 2, 3, 4]
// arr [1, 2, 3, 4]
// index :0: value 1
// index :1: value 2
// index :2: value 3
// index :3: value 4
// elem 1
// elem 2
// elem 3
// elem 4
// arr[0] 1
// arr[1] 2
// arr[2] 3
// arr[3] 4
// dynamic_arr [1]
// dynamic_arr [1, 2, 3, 4]
// index :0: value 1
// index :1: value 2
// index :2: value 3
// index :3: value 4
// elem 1
// elem 2
// elem 3
// elem 4
// arr[0] 1
// arr[1] 2
// arr[2] 3
// arr[3] 4