如何在模式匹配中使用 box 关键字? [英] How do I use the box keyword in pattern matching?
本文介绍了如何在模式匹配中使用 box 关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码显示在 The Rust编程语言:
This code is shown in The Rust Programming Language:
#![feature(box_syntax, box_patterns)]
fn main() {
let b = Some(box 5);
match b {
Some(box n) if n < 0 => {
println!("Box contains negative number {}", n);
}
Some(box n) if n >= 0 => {
println!("Box contains non-negative number {}", n);
}
None => {
println!("No box");
}
_ => unreachable!(),
}
}
但是当我运行它时,出现以下错误:
But when I run it, the following error occurs:
error[E0554]: #[feature] may not be used on the stable release channel
我也试过
fn main() {
let b = Some(box 5);
}
error: box expression syntax is experimental;
是不是因为我的 Rust 版本不是最新的?如何获取 Box::new()
中的内容?我试过了
Is it because my version of Rust is not the latest? How I can get the content in Box::new()
? I tried
fn main() {
let b = Some(Box::new(5));
match b {
Some(Box::new(y)) => print!("{:?}", y),
_ => print!("{:?}", 1),
}
}
error[E0164]: `Box::new` does not name a tuple variant or a tuple struct
--> main.rs:6:14
|
6 | Some(Box::new(y)) => print!("{:?}", y),
| ^^^^^^^^^^^ not a tuple variant or struct
推荐答案
您正在使用 #[feature]
而那些只能与 夜间 Rust 编译器.我认为目前不可能在稳定的 Rust 中匹配 Box
,但 nightly 允许采用以下方式进行匹配(就像您在开始时尝试的那样):
You are using a #[feature]
and those can only be used with a nightly Rust compiler. I don't think it is currently possible to match against a Box
in stable Rust, but nightly allows the following way of doing it (like you attempted in the beginning):
#![feature(box_patterns)]
fn main() {
let b = Some(Box::new(5));
match b {
Some(box y) => print!("{:?}", y),
_ => print!("{:?}", 1),
}
}
这篇关于如何在模式匹配中使用 box 关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文