视频地址
头条地址:https://www.ixigua.com/i6775861706447913485
B站地址:https://www.bilibili.com/video/av81202308/
源码地址
github地址:https://github.com/anonymousGiga/learn_rust
讲解内容
1、忽略模式中的值
(1)使用_忽略整个值
例子:
fn foo(_: i32, y: i32) {
println!("This code only uses the y parameter: {}", y);
}
fn main() {
foo(3, 4);
}
说明:对函数中的参数使用占位符,主要是在实现trait的时候使用(如不需要特征指定函数中的某个参数)。
(2)使用_忽略部分值
let numbers = (2, 4, 8, 16, 32);
match numbers {
(first, _, third, _, fifth) => {
println!("Some numbers: {}, {}, {}", first, third, fifth)
},
}
(3)通过在名字前以一个下划线开头来忽略未使用的变量
例子1:
fn main() {
let _x = 5;
let y = 10;
}
说明:上述代码中,编译时对未使用y警告,对未使用x不会警告。
只使用 _ 和使用以下划线开头的名称有些微妙的不同:比如_x 仍会将值绑定到变量,而 _ 则完全不会绑定。
例子2:
//会报错,因为以下划线开头的变量仍然会绑定值
let s = Some(String::from("Hello!"));
if let Some(_s) = s {
println!("found a string");
}
println!("{:?}", s);
例子3:
//不会报错,因为s的所有权不会移动到\_中
let s = Some(String::from("Hello!"));
if let Some(_) = s {
println!("found a string");
}
println!("{:?}", s);
(4)用..忽略剩余值
对于有多个部分的值,可以使用 .. 语法来只使用部分并忽略其它值
例子1:
fn main() {
let numbers = (2, 4, 8, 16, 32);
match numbers {
(first, .., last) => { //自动匹配到第一个和最后一个值
println!("Some numbers: {}, {}", first, last);
},
}
}
例子2:
//下面的例子错误,因为..匹配必须是无歧义的
fn main() {
let numbers = (2, 4, 8, 16, 32);
match numbers {
(.., second, ..) => {
println!("Some numbers: {}", second)
},
}
}
网友评论