Option 与 Result
None 会变成 null,Err 会变成抛出的 Error。
first_long_word 返回 Option<String>:要么是单词,要么是表示 None 的 null。Option 参数则反过来,把 null 或 undefined 当作 None。
parse_score 返回 Result。Ok 以其值的形式传递,Err 则作为 Error 抛出,错误信息就是该错误的文本。panic 也会变成 Error,但之后模块就无法再使用:请把它当作崩溃处理。
试一试
查找至少有 2 个字母的单词,并把 '100' 和 '-1' 加入列表。[■]words.rs1// None arrives as null, and an Err as a thrown Error.
pub fn first_long_word(text: &str, min: i32) -> Option<String> {
text.split_whitespace()
.find(|word| word.len() as i32 >= min)
.map(|word| word.to_string())
}
pub fn parse_score(text: &str) -> Result<i32, String> {
match text.parse::<i32>() {
Ok(score) if (0..=100).contains(&score) => Ok(score),
Ok(score) => Err(format!("{score} is out of range")),
Err(_) => Err(format!("{text} is not a number")),
}
}
[■]main.js2import {
initNative, firstLongWord, parseScore,
} from './native/words.rs';
await initNative();
console.log(await firstLongWord('import a Rust file', 5));
console.log(await firstLongWord('import a Rust file', 9));
for (const text of ['42', '250', 'abc']) {
try {
console.log(text, 'is', await parseScore(text));
} catch (error) {
console.log(text, 'throws', error.message);
}
}