我正在尝试理解...语法.考虑以下程序:
fn how_many(x: i32) -> &'static str {
match x {
0 => "no oranges",
1 => "an orange",
2 | 3 => "two or three oranges",
9...11 => "approximately 10 oranges",
_ => "few oranges",
}
}
fn pattern_matching() {
for x in 0..13 {
println!("{} : I have {} ", x, how_many(x));
}
}
fn main() {
// println!("{:?}", (2...6));
pattern_matching();
}
Run Code Online (Sandbox Code Playgroud)
在上面的程序中,9...11模式匹配中使用的编译很好.当我尝试使用相同的内容时,println!("{:?}", (2...6));我得到编译错误:
error: `...` syntax cannot be used in expressions
--> src/main.rs:18:24
|
18 | println!("{:?}", (2...6));
| ^^^
|
= help: Use `..` if you need an exclusive range (a < b)
= help: or `..=` if you need an inclusive range (a <= b)
Run Code Online (Sandbox Code Playgroud)
我试图理解为什么不可能在内部使用println.
出于同样的原因,你不能&*$#在表达式中使用:Rust的语法不允许这样做.Rust决定对包含范围使用不同的语法.如果你真的关心完整的细节,你可以阅读有关该问题的所有350多条评论.
该TL; DR:
... 太接近于错字了 .....模式已经稳定,必须永远支持,但它会在某个时候被弃用,并且..=也会优先考虑.该错误消息告诉您使用相应的语法:
Run Code Online (Sandbox Code Playgroud)= help: Use `..` if you need an exclusive range (a < b) = help: or `..=` if you need an inclusive range (a <= b)
fn how_many(x: i32) -> &'static str {
match x {
0 => "no oranges",
1 => "an orange",
2 | 3 => "two or three oranges",
9..=11 => "approximately 10 oranges",
_ => "few oranges",
}
}
fn pattern_matching() {
for x in 0..13 {
println!("{} : I have {} ", x, how_many(x));
}
}
fn main() {
println!("{:?}", 2..=6);
pattern_matching();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
385 次 |
| 最近记录: |