Appearance
Error 1: exercises/error_handling/errors1.rs
题目
rust
// errors1.rs
//
// This function refuses to generate text to be printed on a nametag if you pass
// it an empty string. It'd be nicer if it explained what the problem was,
// instead of just sometimes returning `None`. Thankfully, Rust has a similar
// construct to `Result` that can be used to express error conditions. Let's use
// it!
//
// Execute `rustlings hint errors1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
pub fn generate_nametag_text(name: String) -> Option<String> {
if name.is_empty() {
// Empty names aren't allowed.
None
} else {
Some(format!("Hi! My name is {}", name))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generates_nametag_text_for_a_nonempty_name() {
assert_eq!(
generate_nametag_text("Beyoncé".into()),
Ok("Hi! My name is Beyoncé".into())
);
}
#[test]
fn explains_why_generating_nametag_text_fails() {
assert_eq!(
generate_nametag_text("".into()),
// Don't change this line
Err("`name` was empty; it must be nonempty.".into())
);
}
}
如果您向函数传递空字符串,则函数会拒绝生成打印名字的文本。如果能够通过错误解释到底问题处在哪里,而不是只返回None
,那样是最好的。
庆幸的是,Rust有一个与Result
类似的结构,可以用来表达错误条件,让我们使用它吧。
题目解析
Ok
和Err
是Result
的变体之一,所以单元测试的意思是generate_nametag_text
应该返回一个Result
,而不是一个Option
。
要对此做修改,您需要:
- 将函数签名的返回值类型修改为
Result<String, String>
,可能返回Ok(String)
或者Err(String)
- 更改函数体,将返回
Some(string)
的地方修改为Ok(string)
,将返回None
的地方修改为Err(String)
。
修改后如下:
rust
pub fn generate_nametag_text(name: String) -> Option<String> {
pub fn generate_nametag_text(name: String) -> Result<String, String> {
if name.is_empty() {
// Empty names aren't allowed.
None
Err("`name` was empty; it must be nonempty.".to_string())
} else {
Some(format!("Hi! My name is {}", name))
Ok(format!("Hi! My name is {}", name))
}
}