2个版本
0.0.1 | 2020年4月7日 |
---|---|
0.0.0 | 2020年4月7日 |
#25 in #returning
用于 no_error
3KB
50 行
no_error
为no_std
+ no_alloc
Rust的错误库
- 宏将字符串字面量转换为C风格字符数组
- 不需要分配器
- 支持非C字符串文本(即 len + string)
- 如果文本不是选项,则支持错误代码
use no_error::*;
extern "C" {
fn print(x: const *u8); // takes in a c-string
fn print_with_len(x: const *u8, len usize); // takes in text and length
}
const FAIL:ErrorCode = 42;
fn can_fail(i:i32) -> Result<()> {
if i < 0 {
// programmatically appends a "/0" to end of static string
error_message!("a failure happened","it happened in can_fail()")
} else if i == 0 {
// don't like c strings? supports failure codes too
error_code!(FAIL)
} else {
// you don't have to specify the source if you don't want
error_message!("a failure happened")
}
}
fn main() {
match can_fail(42) {
Ok(_) => (),
Err(a) => {
print(a.cstr_description());
let source = a.source();
print_with_len(source.as_ptr(),source.len());
if let Some(c) = a.code() {
if c == FAIL {
print("secret of life".as_ptr());
}
}
},
};
}
依赖项
~5KB