Appearance
测验3: exercises/quiz3.rs
题目
rust
// quiz3.rs
//
// This quiz tests:
// - Generics
// - Traits
//
// An imaginary magical school has a new report card generation system written
// in Rust! Currently the system only supports creating report cards where the
// student's grade is represented numerically (e.g. 1.0 -> 5.5). However, the
// school also issues alphabetical grades (A+ -> F-) and needs to be able to
// print both types of report card!
//
// Make the necessary code changes in the struct ReportCard and the impl block
// to support alphabetical report cards. Change the Grade in the second test to
// "A+" to show that your changes allow alphabetical grades.
//
// Execute `rustlings hint quiz3` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
pub struct ReportCard {
pub grade: f32,
pub student_name: String,
pub student_age: u8,
}
impl ReportCard {
pub fn print(&self) -> String {
format!("{} ({}) - achieved a grade of {}",
&self.student_name, &self.student_age, &self.grade)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generate_numeric_report_card() {
let report_card = ReportCard {
grade: 2.1,
student_name: "Tom Wriggle".to_string(),
student_age: 12,
};
assert_eq!(
report_card.print(),
"Tom Wriggle (12) - achieved a grade of 2.1"
);
}
#[test]
fn generate_alphabetic_report_card() {
// TODO: Make sure to change the grade here after you finish the exercise.
let report_card = ReportCard {
grade: 2.1,
student_name: "Gary Plotter".to_string(),
student_age: 11,
};
assert_eq!(
report_card.print(),
"Gary Plotter (11) - achieved a grade of A+"
);
}
}
本次测验涉及的内容:
- 泛型
- Trait
一个虚构的魔法学校,有一个用Rust编写的新成绩单生成系统!目前系统只支持创建以数字表示学生成绩的成绩单(比如1.0 -> 5.5)。然而,学校也按照字母顺序颁发成绩(A+ -> F-),并且需要能够打印两种类型的成绩单。
在ReportCard
结构体和impl
块中进行必要的代码修改,以支持字母顺序的成绩单。将第二次测试中的成绩更改为A+
,以表明您的更改已生效。
题目解析
我们先修改ReportCard
结构体,让它先支持泛型,以便能够同时支持浮点数和字符串。
rust
pub struct ReportCard {
pub grade: f32,
pub struct ReportCard<T> {
pub grade: T,
pub student_name: String,
pub student_age: u8,
}
接着,我们还要看impl
块,在print
方法中,我们使用了{}
输出,这就要求grade
这个泛型参数需要首先实现了std::fmt::Display
Trait。
rust
impl ReportCard {
impl<T: std::fmt::Display> ReportCard<T> {
pub fn print(&self) -> String {
format!(
"{} ({}) - achieved a grade of {}",
&self.student_name, &self.student_age, &self.grade
)
}
}
最后我们还需要把单元测试里面的第二个成绩修改为A+
:
rust
#[test]
fn generate_alphabetic_report_card() {
// TODO: Make sure to change the grade here after you finish the exercise.
let report_card = ReportCard {
grade: 2.1,
grade: "A+",
student_name: "Gary Plotter".to_string(),
student_age: 11,
};
assert_eq!(
report_card.print(),
"Gary Plotter (11) - achieved a grade of A+"
);
}