gpt4 book ai didi

Rust 选项,实现自定义 "expect"方法

转载 作者:行者123 更新时间:2023-11-29 07:57:49 24 4
gpt4 key购买 nike

我是 Rust 的新手,所以我必须警告你,我不是 100% 确定我在做什么。在一个 rust-sfml 示例(与问题无关)中,我看到了这个 Options 模式,这显然是一个常见的模式:

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

我不知道该怎么办:(我希望更有知识的人能指出我的错误。

感谢您的宝贵时间!

最佳答案

有几种方法可以修复您的函数:第一种是在 err 上添加一个 'static 生命周期注释:

fn checkOption<T>(obj: Option<T>, err: &'static str) -> T {
match obj {
Some(o) => return o,
None => panic!(err)
}
}

但是,这意味着您只能为 err 使用类型为 &'static str 的值(即有效的字符串常量)。

第二种方法是做 expect 做的事并调用 panic!("{}", err) 而不是 panic!(err):

fn checkOption<T>(obj: Option<T>, err: &str) -> T {
match obj {
Some(o) => return o,
None => panic!("{}", err)
}
}

关于Rust 选项,实现自定义 "expect"方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29457617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com