【发布时间】:2015-04-05 13:08:11
【问题描述】:
我对 Rust 很陌生,所以我必须警告你,我不是 100% 确定我在做什么。在一个 rust-sfml 示例(与问题无关)中,我看到了这个选项模式,这显然是一个常见的模式:
let ballSoundBuffer = match SoundBuffer::new("resources/ball.wav") {
Some(ballSoundBuffer) => ballSoundBuffer,
None => panic!("Cannot load Ball sound buffer.")
};
后来我了解了expect()函数,所以上面可以替换为:
let ballSoundBuffer = SoundBuffer::new("resources/ball.wav").expect("Cannot load Ball sound buffer.")
为了练习,我想自己实现类似 expect 方法的东西,作为一个独立的方法,并想出了这样的东西:
fn checkOption<T>(obj: Option<T>, err: &str) -> T {
match obj {
Some(o) => return o,
None => panic!(err)
}
}
我们的目标是:
let tmp = SoundBuffer::new("resources/ball.wav");
let ballSoundBuffer = checkOption(tmp, "Cannot load Ball sound buffer.");
我使用泛型是因为我还希望该方法与 SoundBuffer 以外的其他资源一起使用(但它们在加载它们时也使用相同的选项模式)。但是,这根本不起作用:
src/main.rs:20:24: 20:27 error: cannot infer an appropriate lifetime due to conflicting requirements
src/main.rs:20 None => panic!(err)
^~~
<std macros>:1:1: 12:62 note: in expansion of panic!
src/main.rs:20:17: 21:6 note: expansion site
src/main.rs:17:51: 22:2 note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the block at 17:50...
src/main.rs:17 fn checkOption<T>(obj: Option<T>, err: &str) -> T {
src/main.rs:18 match obj {
src/main.rs:19 Some(o) => return o,
src/main.rs:20 None => panic!(err)
src/main.rs:21 }
src/main.rs:22 }
src/main.rs:20:24: 20:27 note: ...so that expression is assignable (expected `&str`, found `&str`)
src/main.rs:20 None => panic!(err)
^~~
<std macros>:1:1: 12:62 note: in expansion of panic!
src/main.rs:20:17: 21:6 note: expansion site
note: but, the lifetime must be valid for the static lifetime...
<std macros>:3:1: 3:28 note: ...so that the type `&str` will meet its required lifetime bounds
<std macros>:3 $ crate:: rt:: begin_unwind (
^~~~~~~~~~~~~~~~~~~~~~~~~~~
<std macros>:1:1: 12:62 note: in expansion of panic!
src/main.rs:20:17: 21:6 note: expansion site
error: aborting due to previous error
我不知道该怎么办 :( 我希望有更多知识的人能指出我的错误。
感谢您的宝贵时间!
【问题讨论】:
-
我向
panic!提交了关于使用非字符串作为第一个参数的糟糕错误消息的issue a while back。