Rustlings 解题记录
Rustlings 解题记录
Intro
// intro2.rs
fn main() {
let world = "world";
println!("Hello {}!",world);
}
Variables
// variables1.rs
fn main() {
let x = 5;
println!("x has the value {}", x);
}
// variables2.rs
fn main() {
let x = 10;
if x == 10 {
println!("x is ten!");
} else {
println!("x is not ten!");
}
}
// variables3.rs
fn main() {
let x: i32 = 42;
println!("Number {}", x);
}
// variables4.rs
fn main() {
let mut x = 3;
println!("Number {}", x);
x = 5; // don't change this line
println!("Number {}", x);
}
// variables5.rs
fn main() {
let number = "T-H-R-E-E"; // don't change this line
println!("Spell a Number : {}", number);
let number = 3; // don't rename this variable
println!("Number plus two is : {}", number + 2);
}
// variables6.rs
const NUMBER:i32 = 3;
fn main() {
println!("Number {}", NUMBER);
}
Functions
// functions1.rs
fn main() {
call_me();
}
fn call_me(){
}
// functions2.rs
fn main() {
call_me(3);
}
fn call_me(num:i32) {
for i in 0..num {
println!("Ring! Call number {}", i + 1);
}
}
// functions3.rs
fn main() {
call_me(10);
}
fn call_me(num: u32) {
for i in 0..num {
println!("Ring! Call number {}", i + 1);
}
}
// functions4.rs
fn main() {
let original_price = 51;
println!("Your sale price is {}", sale_price(original_price));
}
fn sale_price(price: i32) -> i32{
if is_even(price) {
price - 10
} else {
price - 3
}
}
fn is_even(num: i32) -> bool {
num % 2 == 0
}
// functions5.rs
fn main() {
let answer = square(3);
println!("The square of 3 is {}", answer);
}
fn square(num: i32) -> i32 {
num * num
}
If
// if1.rs
pub fn bigger(a: i32, b: i32) -> i32 {
if a > b{
a
}else{
b
}
}
// if2.rs
pub fn foo_if_fizz(fizzish: &str) -> &str {
if fizzish == "fizz" {
"foo"
} else if fizzish == "fuzz"{
"bar"
}else{
"baz"
}
}
// if3.rs
pub fn animal_habitat(animal: &str) -> &'static str {
let identifier = if animal == "crab" {
1
} else if animal == "gopher" {
2
} else if animal == "snake" {
3
} else {
4
};
// DO NOT CHANGE THIS STATEMENT BELOW
let habitat = if identifier == 1 {
"Beach"
} else if identifier == 2 {
"Burrow"
} else if identifier == 3 {
"Desert"
} else {
"Unknown"
};
habitat
}
Quiz
// quiz1.rs
// Put your function here!
fn calculate_price_of_apples(num:i32) -> i32{
if num > 40 {
num
}else{
2 * num
}
}
// Don't modify this function!
#[test]
fn verify_test() {
let price1 = calculate_price_of_apples(35);
let price2 = calculate_price_of_apples(40);
let price3 = calculate_price_of_apples(41);
let price4 = calculate_price_of_apples(65);
assert_eq!(70, price1);
assert_eq!(80, price2);
assert_eq!(41, price3);
assert_eq!(65, price4);
}
// quiz2.rs
pub enum Command {
Uppercase,
Trim,
Append(usize),
}
mod my_module {
use super::Command;
// TODO: Complete the function signature!
pub fn transformer(input: Vec<(String,Command)>) -> Vec<String> {
// TODO: Complete the output declaration!
let mut output: Vec<String> = vec![];
for (string, command) in input.iter() {
let mut str = string.clone();
// TODO: Complete the function body. You can do it!
match command {
Command::Uppercase => {
str = str.to_uppercase();
},
Command::Trim =>{
str = str.trim().to_string();
},
Command::Append(s) => {
for _i in 0..(*s).into(){
str.push_str("bar");
}
}
}
output.push(str);
}
output
}
}
Primitive_types
// primitive_types1.rs
fn main() {
// Booleans (`bool`)
let is_morning = true;
if is_morning {
println!("Good morning!");
}
let is_evening = !is_morning;// Finish the rest of this line like the example! Or make it be false!
if is_evening {
println!("Good evening!");
}
}
// primitive_types2.rs
fn main() {
// Characters (`char`)
// Note the _single_ quotes, these are different from the double quotes
// you've been seeing around.
let my_first_initial = 'C';
if my_first_initial.is_alphabetic() {
println!("Alphabetical!");
} else if my_first_initial.is_numeric() {
println!("Numerical!");
} else {
println!("Neither alphabetic nor numeric!");
}
let your_character = '1';// Finish this line like the example! What's your favorite character?
// Try a letter, try a number, try a special character, try a character
// from a different language than your own, try an emoji!
if your_character.is_alphabetic() {
println!("Alphabetical!");
} else if your_character.is_numeric() {
println!("Numerical!");
} else {
println!("Neither alphabetic nor numeric!");
}
}
// primitive_types3.rs
fn main() {
let a = [0;120];
if a.len() >= 100 {
println!("Wow, that's a big array!");
} else {
println!("Meh, I eat arrays like that for breakfast.");
}
}
// primitive_types4.rs
#[test]
fn slice_out_of_array() {
let a = [1, 2, 3, 4, 5];
let nice_slice = &a[1..4];
assert_eq!([2, 3, 4], nice_slice)
}
// primitive_types5.rs
fn main() {
let cat = ("Furry McFurson", 3.5);
let (name, age) = cat;
println!("{} is {} years old.", name, age);
}
// primitive_types6.rs
#[test]
fn indexing_tuple() {
let numbers = (1, 2, 3);
// Replace below ??? with the tuple indexing syntax.
let second = numbers.1;
assert_eq!(2, second,
"This is not the 2nd number in the tuple!")
}
Vecs
// vecs1.rs
fn array_and_vec() -> ([i32; 4], Vec<i32>) {
let a = [10, 20, 30, 40]; // a plain array
let v = vec![10, 20, 30, 40];// TODO: declare your vector here with the macro for vectors
(a, v)
}
// vecs2.rs
fn vec_loop(mut v: Vec<i32>) -> Vec<i32> {
for element in v.iter_mut() {
// TODO: Fill this up so that each element in the Vec `v` is
// multiplied by 2.
(*element) *= 2;
}
// At this point, `v` should be equal to [4, 8, 12, 16, 20].
v
}
fn vec_map(v: &Vec<i32>) -> Vec<i32> {
v.iter().map(|element| {
// TODO: Do the same thing as above - but instead of mutating the
// Vec, you can just return the new number!
element * 2
}).collect()
}
// quiz3.rs
use std::fmt::Display;
pub struct ReportCard<T> {
pub grade: T,
pub student_name: String,
pub student_age: u8,
}
impl<T: Display> ReportCard<T> {
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: "A+",
student_name: "Gary Plotter".to_string(),
student_age: 11,
};
assert_eq!(
report_card.print(),
"Gary Plotter (11) - achieved a grade of A+"
);
}
}
Move_semantics
// move_semantics1.rs
fn main() {
let vec0 = Vec::new();
let mut vec1 = fill_vec(vec0);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
vec1.push(88);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec;
vec.push(22);
vec.push(44);
vec.push(66);
vec
}
// move_semantics2.rs
fn main() {
let vec0 = Vec::new();
let mut vec1 = fill_vec(&vec0);
println!("{} has length {}, with contents: `{:?}`", "vec0", vec0.len(), vec0);
vec1.push(88);
println!("{} has length {}, with contents `{:?}`", "vec1", vec1.len(), vec1);
}
fn fill_vec(vec: &Vec<i32>) -> Vec<i32> {
let mut vec = vec.to_vec();
vec.push(22);
vec.push(44);
vec.push(66);
vec
}
// move_semantics3.rs
fn main() {
let vec0 = Vec::new();
let mut vec1 = fill_vec(vec0);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
vec1.push(88);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}
fn fill_vec(mut vec: Vec<i32>) -> Vec<i32> {
vec.push(22);
vec.push(44);
vec.push(66);
vec
}
// move_semantics4.rs
fn main() {
// let vec0 = Vec::new();
let mut vec1 = fill_vec();
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
vec1.push(88);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}
// `fill_vec()` no longer takes `vec: Vec<i32>` as argument
fn fill_vec() -> Vec<i32> {
let mut vec = Vec::new();
vec.push(22);
vec.push(44);
vec.push(66);
vec
}
// move_semantics5.rs
fn main() {
let mut x = 100;
let y = &mut x;
*y += 100;
let z = &mut x;
*z += 1000;
assert_eq!(x, 1200);
}
// move_semantics6.rs
fn main() {
let data = "Rust is great!".to_string();
get_char(&data);
string_uppercase(data);
}
// Should not take ownership
fn get_char(data: &String) -> char {
data.chars().last().unwrap()
}
// Should take ownership
fn string_uppercase(mut data: String) {
data = data.to_uppercase();
println!("{}", data);
}
Structs
// structs1.rs
struct ColorClassicStruct {
// TODO: Something goes here
pub red:u8,
pub green:u8,
pub blue:u8,
}
struct ColorTupleStruct(u8,u8,u8);
#[derive(Debug)]
struct UnitLikeStruct;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classic_c_structs() {
// TODO: Instantiate a classic c struct!
let green = ColorClassicStruct{
red:0,
green:255,
blue:0,
};
assert_eq!(green.red, 0);
assert_eq!(green.green, 255);
assert_eq!(green.blue, 0);
}
#[test]
fn tuple_structs() {
// TODO: Instantiate a tuple struct!
let green = (0,255,0);
assert_eq!(green.0, 0);
assert_eq!(green.1, 255);
assert_eq!(green.2, 0);
}
#[test]
fn unit_structs() {
// TODO: Instantiate a unit-like struct!
let unit_like_struct = UnitLikeStruct{};
let message = format!("{:?}s are fun!", unit_like_struct);
assert_eq!(message, "UnitLikeStructs are fun!");
}
}
// structs2.rs
#[derive(Debug)]
struct Order {
name: String,
year: u32,
made_by_phone: bool,
made_by_mobile: bool,
made_by_email: bool,
item_number: u32,
count: u32,
}
fn create_order_template() -> Order {
Order {
name: String::from("Bob"),
year: 2019,
made_by_phone: false,
made_by_mobile: false,
made_by_email: true,
item_number: 123,
count: 0,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn your_order() {
let order_template = create_order_template();
// TODO: Create your own order using the update syntax and template above!
let your_order = Order {
name: String::from("Hacker in Rust"),
year: 2019,
made_by_phone: false,
made_by_mobile: false,
made_by_email: true,
item_number: 123,
count: 1,
};
assert_eq!(your_order.name, "Hacker in Rust");
assert_eq!(your_order.year, order_template.year);
assert_eq!(your_order.made_by_phone, order_template.made_by_phone);
assert_eq!(your_order.made_by_mobile, order_template.made_by_mobile);
assert_eq!(your_order.made_by_email, order_template.made_by_email);
assert_eq!(your_order.item_number, order_template.item_number);
assert_eq!(your_order.count, 1);
}
}
// structs3.rs
#[derive(Debug)]
struct Package {
sender_country: String,
recipient_country: String,
weight_in_grams: i32,
}
impl Package {
fn new(sender_country: String, recipient_country: String, weight_in_grams: i32) -> Package {
if weight_in_grams <= 0 {
panic!("Can not ship a weightless package.")
} else {
Package {
sender_country,
recipient_country,
weight_in_grams,
}
}
}
fn is_international(&self) -> bool {
// Something goes here...
!self.sender_country.eq(&self.recipient_country)
}
fn get_fees(&self, cents_per_gram: i32) -> i32 {
// Something goes here...
self.weight_in_grams * cents_per_gram
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn fail_creating_weightless_package() {
let sender_country = String::from("Spain");
let recipient_country = String::from("Austria");
Package::new(sender_country, recipient_country, -2210);
}
#[test]
fn create_international_package() {
let sender_country = String::from("Spain");
let recipient_country = String::from("Russia");
let package = Package::new(sender_country, recipient_country, 1200);
assert!(package.is_international());
}
#[test]
fn create_local_package() {
let sender_country = String::from("Canada");
let recipient_country = sender_country.clone();
let package = Package::new(sender_country, recipient_country, 1200);
assert!(!package.is_international());
}
#[test]
fn calculate_transport_fees() {
let sender_country = String::from("Spain");
let recipient_country = String::from("Spain");
let cents_per_gram = 3;
let package = Package::new(sender_country, recipient_country, 1500);
assert_eq!(package.get_fees(cents_per_gram), 4500);
assert_eq!(package.get_fees(cents_per_gram * 2), 9000);
}
}
Enum
// enums1.rs
#[derive(Debug)]
enum Message {
// TODO: define a few types of messages as used below
Quit,
Echo,
Move,
ChangeColor,
}
// enums2.rs
#[derive(Debug)]
enum Message {
// TODO: define the different variants used below
Move{
x:i32,
y:i32,
},
Echo(String),
ChangeColor(u8,u8,u8),
Quit,
}
// enums3.rs
enum Message {
// TODO: implement the message variant types based on their usage below
Move(Point),
Echo(String),
ChangeColor(u8,u8,u8),
Quit,
}
struct Point {
x: u8,
y: u8,
}
struct State {
color: (u8, u8, u8),
position: Point,
quit: bool,
message: String
}
impl State {
fn change_color(&mut self, color: (u8, u8, u8)) {
self.color = color;
}
fn quit(&mut self) {
self.quit = true;
}
fn echo(&mut self, s: String) { self.message = s }
fn move_position(&mut self, p: Point) {
self.position = p;
}
fn process(&mut self, message: Message) {
// TODO: create a match expression to process the different message
// variants
// Remember: When passing a tuple as a function argument, you'll need
// extra parentheses: fn function((t, u, p, l, e))
match message {
Message::Move(p) => self.move_position(p),
Message::Echo(s) => self.echo(s),
Message::ChangeColor(r,g,b) => self.change_color((r,g,b)),
Message::Quit => self.quit(),
};
}
}
Strings
// strings1.rs
fn main() {
let answer = current_favorite_color();
println!("My current favorite color is {}", answer);
}
fn current_favorite_color() -> String {
"blue".to_string()
}
// strings2.rs
fn main() {
let word = String::from("green"); // Try not changing this line :)
if is_a_color_word(&word) {
println!("That is a color word I know!");
} else {
println!("That is not a color word I know.");
}
}
fn is_a_color_word(attempt: &str) -> bool {
attempt == "green" || attempt == "blue" || attempt == "red"
}
// strings3.rs
fn trim_me(input: &str) -> String {
// TODO: Remove whitespace from both ends of a string!
input.trim().to_string()
}
fn compose_me(input: &str) -> String {
// TODO: Add " world!" to the string! There's multiple ways to do this!
input.to_string() + " world!"
}
fn replace_me(input: &str) -> String {
// TODO: Replace "cars" in the string with "balloons"!
input.replace("cars","balloons")
}
// strings4.rs
fn string_slice(arg: &str) {
println!("{}", arg);
}
fn string(arg: String) {
println!("{}", arg);
}
fn main() {
string_slice("blue");
string("red".to_string());
string(String::from("hi"));
string("rust is fun!".to_owned());
string("nice weather".into());
string(format!("Interpolation {}", "Station"));
string_slice(&String::from("abc")[0..1]);
string_slice(" hello there ".trim());
string("Happy Monday!".to_string().replace("Mon", "Tues"));
string("mY sHiFt KeY iS sTiCkY".to_lowercase());
}
Modules
// modules1.rs
mod sausage_factory {
// Don't let anybody outside of this module see this!
fn get_secret_recipe() -> String {
String::from("Ginger")
}
pub fn make_sausage() {
get_secret_recipe();
println!("sausage!");
}
}
fn main() {
sausage_factory::make_sausage();
}
// modules2.rs
mod delicious_snacks {
// TODO: Fix these use statements
pub use self::fruits::PEAR as fruit;
pub use self::veggies::CUCUMBER as veggie;
mod fruits {
pub const PEAR: &'static str = "Pear";
pub const APPLE: &'static str = "Apple";
}
mod veggies {
pub const CUCUMBER: &'static str = "Cucumber";
pub const CARROT: &'static str = "Carrot";
}
}
fn main() {
println!(
"favorite snacks: {} and {}",
delicious_snacks::fruit,
delicious_snacks::veggie
);
}
// modules3.rs
// TODO: Complete this use statement
use std::time::{SystemTime,UNIX_EPOCH};
fn main() {
match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
}
}
Hashmap
// hashmaps1.rs
use std::collections::HashMap;
fn fruit_basket() -> HashMap<String, u32> {
let mut basket = HashMap::<String, u32>::new();// TODO: declare your hash map here.
// Two bananas are already given for you :)
basket.insert(String::from("banana"), 2);
// TODO: Put more fruits in your basket here.
basket.insert(String::from("apple"), 3);
basket.insert(String::from("orange"), 3);
basket
}
// hashmaps2.rs
use std::collections::HashMap;
#[derive(Hash, PartialEq, Eq)]
enum Fruit {
Apple,
Banana,
Mango,
Lychee,
Pineapple,
}
fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
let fruit_kinds = vec![
Fruit::Apple,
Fruit::Banana,
Fruit::Mango,
Fruit::Lychee,
Fruit::Pineapple,
];
for fruit in fruit_kinds {
// TODO: Insert new fruits if they are not already present in the
// basket. Note that you are not allowed to put any type of fruit that's
// already present!
if !basket.contains_key(&fruit){
basket.insert(fruit,2);
}
}
}
// hashmaps3.rs
use std::collections::HashMap;
// A structure to store the goal details of a team.
struct Team {
goals_scored: u8,
goals_conceded: u8,
}
fn build_scores_table(results: String) -> HashMap<String, Team> {
// The name of the team is the key and its associated struct is the value.
let mut scores: HashMap<String, Team> = HashMap::new();
for r in results.lines() {
let v: Vec<&str> = r.split(',').collect();
let team_1_name = v[0].to_string();
let team_1_score: u8 = v[2].parse().unwrap();
let team_2_name = v[1].to_string();
let team_2_score: u8 = v[3].parse().unwrap();
// TODO: Populate the scores table with details extracted from the
// current line. Keep in mind that goals scored by team_1
// will be the number of goals conceded from team_2, and similarly
// goals scored by team_2 will be the number of goals conceded by
// team_1.
let team_1 = match scores.get(&team_1_name) {
None => Team{
goals_scored:team_1_score,
goals_conceded:team_2_score,
},
Some(t) => Team{
goals_scored: t.goals_scored + team_1_score,
goals_conceded: t.goals_conceded + team_2_score,
}
};
let team_2 = match scores.get(&team_2_name) {
None => Team{
goals_scored:team_2_score,
goals_conceded:team_1_score,
},
Some(t) => Team{
goals_scored: t.goals_scored + team_2_score,
goals_conceded: t.goals_conceded + team_1_score,
}
};
scores.insert(team_1_name,team_1);
scores.insert(team_2_name,team_2);
}
scores
}
Options
// options1.rs
// This function returns how much icecream there is left in the fridge.
// If it's before 10PM, there's 5 pieces left. At 10PM, someone eats them
// all, so there'll be no more left :(
fn maybe_icecream(time_of_day: u16) -> Option<u16> {
// We use the 24-hour system here, so 10PM is a value of 22 and 12AM is a
// value of 0 The Option output should gracefully handle cases where
// time_of_day > 23.
// TODO: Complete the function body - remember to return an Option!
if time_of_day < 22 && time_of_day >= 0{
Some(5)
}else if time_of_day <= 24 && time_of_day >= 22{
Some(0)
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn check_icecream() {
assert_eq!(maybe_icecream(9), Some(5));
assert_eq!(maybe_icecream(10), Some(5));
assert_eq!(maybe_icecream(23), Some(0));
assert_eq!(maybe_icecream(22), Some(0));
assert_eq!(maybe_icecream(25), None);
}
#[test]
fn raw_value() {
// TODO: Fix this test. How do you get at the value contained in the
// Option?
let icecreams = maybe_icecream(12).unwrap();
assert_eq!(icecreams, 5);
}
}
// options2.rs
#[cfg(test)]
mod tests {
#[test]
fn simple_option() {
let target = "rustlings";
let optional_target = Some(target);
// TODO: Make this an if let statement whose value is "Some" type
if let Some(word) = optional_target {
assert_eq!(word, target);
}
}
#[test]
fn layered_option() {
let range = 10;
let mut optional_integers: Vec<Option<i8>> = vec![None];
for i in 1..(range + 1) {
optional_integers.push(Some(i));
}
let mut cursor = range;
// TODO: make this a while let statement - remember that vector.pop also
// adds another layer of Option<T>. You can stack `Option<T>`s into
// while let and if let.
while let Some(Some(integer)) = optional_integers.pop() {
assert_eq!(integer, cursor);
cursor -= 1;
}
assert_eq!(cursor, 0);
}
}
// options3.rs
struct Point {
x: i32,
y: i32,
}
fn main() {
let y: Option<Point> = Some(Point { x: 100, y: 200 });
match &y {
Some(p) => println!("Co-ordinates are {},{} ", &p.x, p.y),
_ => panic!("no match!"),
}
y; // Fix without deleting this line.
}
Errors
// errors1.rs
pub fn generate_nametag_text(name: String) -> Result<String,String> {
if name.is_empty() {
// Empty names aren't allowed.
Err("`name` was empty; it must be nonempty.".into())
} else {
Ok(format!("Hi! My name is {}", name))
}
}
// errors2.rs
use std::num::ParseIntError;
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1;
let cost_per_item = 5;
let qty = item_quantity.parse::<i32>()?;
Ok(qty * cost_per_item + processing_fee)
}
// errors3.rs
use std::num::ParseIntError;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut tokens = 100;
let pretend_user_input = "8";
let cost = total_cost(pretend_user_input)?;
if cost > tokens {
println!("You can't afford that many!");
} else {
tokens -= cost;
println!("You now have {} tokens.", tokens);
}
Ok(())
}
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1;
let cost_per_item = 5;
let qty = item_quantity.parse::<i32>()?;
Ok(qty * cost_per_item + processing_fee)
}
// errors4.rs
#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);
#[derive(PartialEq, Debug)]
enum CreationError {
Negative,
Zero,
}
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
// Hmm...? Why is this only returning an Ok value?
if value == 0 {
Err(CreationError::Zero)
}else if value < 0{
Err(CreationError::Negative)
}else{
Ok(PositiveNonzeroInteger(value as u64))
}
}
}
// errors5.rs
use std::error;
use std::fmt;
use std::num::ParseIntError;
// TODO: update the return type of `main()` to make this compile.
fn main() -> Result<(), Box<dyn std::error::Error>> {
let pretend_user_input = "42";
let x: i64 = pretend_user_input.parse()?;
println!("output={:?}", PositiveNonzeroInteger::new(x)?);
Ok(())
}
// errors6.rs
use std::num::ParseIntError;
// This is a custom error type that we will be using in `parse_pos_nonzero()`.
#[derive(PartialEq, Debug)]
enum ParsePosNonzeroError {
Creation(CreationError),
ParseInt(ParseIntError),
}
impl ParsePosNonzeroError {
fn from_creation(err: CreationError) -> ParsePosNonzeroError {
ParsePosNonzeroError::Creation(err)
}
// TODO: add another error conversion function here.
fn from_parseint(err: ParseIntError) -> ParsePosNonzeroError{
ParsePosNonzeroError::ParseInt(err)
}
}
fn parse_pos_nonzero(s: &str) -> Result<PositiveNonzeroInteger, ParsePosNonzeroError> {
// TODO: change this to return an appropriate error instead of panicking
// when `parse()` returns an error.
// let x: i64 = match s.parse() {
// Ok(x) => x,
// Err(e) => {
// return Err(ParsePosNonzeroError::from_parseint(e));
// }
// };
let x: i64 = s.parse().map_err(ParsePosNonzeroError::from_parseint)?;
PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation)
}
Generics
// generics1.rs
fn main() {
let mut shopping_list: Vec<&str> = Vec::new();
shopping_list.push("milk");
}
// generics2.rs
struct Wrapper<T> {
value: T,
}
impl<T> Wrapper<T> {
pub fn new(value: T) -> Self {
Wrapper { value }
}
}
Traits
// traits1.rs
trait AppendBar {
fn append_bar(self) -> Self;
}
impl AppendBar for String {
// TODO: Implement `AppendBar` for type `String`.
fn append_bar(self) -> String{
self + "Bar"
}
}
// traits2.rs
trait AppendBar {
fn append_bar(self) -> Self;
}
// TODO: Implement trait `AppendBar` for a vector of strings.
impl AppendBar for Vec<String>{
fn append_bar(mut self) -> Vec<String> {
self.push(String::from("Bar"));
self
}
}
// traits3.rs
pub trait Licensed {
fn licensing_info(&self) -> String{
String::from("Some information")
}
}
// traits4.rs
// YOU MAY ONLY CHANGE THE NEXT LINE
fn compare_license_types(software: impl Licensed, software_two: impl Licensed) -> bool {
software.licensing_info() == software_two.licensing_info()
}
// traits5.r
// YOU MAY ONLY CHANGE THE NEXT LINE
fn some_func(item: impl SomeTrait + OtherTrait ) -> bool {
item.some_function() && item.other_function()
}
Lifetimes
// lifetimes1.rs
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
// lifetimes2.rs
fn main() {
let string1 = String::from("long string is long");
let string2;
let result;
{
string2 = String::from("xyz");
result = longest(string1.as_str(), string2.as_str());
}
println!("The longest string is '{}'", result);
}
// lifetimes3.rs
struct Book<'a> {
author: &'a str,
title: &'a str,
}
Tests
// tests1.rs
#[cfg(test)]
mod tests {
#[test]
fn you_can_assert() {
assert!(true);
}
}
// tests2.rs
mod tests {
#[test]
fn you_can_assert_eq() {
assert_eq!(1,1);
}
}
// tests3.rs
pub fn is_even(num: i32) -> bool {
num % 2 == 0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn is_true_when_even() {
assert!(is_even(6));
}
#[test]
fn is_false_when_odd() {
assert!(!is_even(5));
}
}
// tests4.rs
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn correct_width_and_height() {
// This test should check if the rectangle is the size that we pass into its constructor
let rect = Rectangle::new(10, 20);
assert_eq!(rect.width, 10); // check width
assert_eq!(rect.height, 20); // check height
}
#[test]
#[should_panic]
fn negative_width() {
// This test should check if program panics when we try to create rectangle with negative width
let _rect = Rectangle::new(-10, 10);
}
#[test]
#[should_panic]
fn negative_height() {
// This test should check if program panics when we try to create rectangle with negative height
let _rect = Rectangle::new(10, -10);
}
}
// tests5.rs
unsafe fn modify_by_address(address: usize) {
// TODO: Fill your safety notice of the code block below to match your
// code's behavior and the contract of this function. You may use the
// comment of the test below as your format reference.
unsafe {
*(address as *mut u32) = 0xAABBCCDD;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_success() {
let mut t: u32 = 0x12345678;
// SAFETY: The address is guaranteed to be valid and contains
// a unique reference to a `u32` local variable.
unsafe { modify_by_address(&mut t as *mut u32 as usize) };
assert!(t == 0xAABBCCDD);
}
}
// tests6.rs
struct Foo {
a: u128,
b: Option<String>,
}
/// # Safety
///
/// The `ptr` must contain an owned box of `Foo`.
unsafe fn raw_pointer_to_box(ptr: *mut Foo) -> Box<Foo> {
// SAFETY: The `ptr` contains an owned box of `Foo` by contract. We
// simply reconstruct the box from that pointer.
let mut ret: Box<Foo> = unsafe {
Box::from_raw(ptr)
};
// todo!("The rest of the code goes here")
(*ret).b = Some("hello".to_string());
ret
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Instant;
#[test]
fn test_success() {
let data = Box::new(Foo { a: 1, b: None });
let ptr_1 = &data.a as *const u128 as usize;
// SAFETY: We pass an owned box of `Foo`.
let ret = unsafe { raw_pointer_to_box(Box::into_raw(data)) };
let ptr_2 = &ret.a as *const u128 as usize;
assert!(ptr_1 == ptr_2);
assert!(ret.b == Some("hello".to_owned()));
}
}
Iterators
// iterators1.rs
fn main() {
let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"];
let mut my_iterable_fav_fruits = my_fav_fruits.iter(); // TODO: Step 1
assert_eq!(my_iterable_fav_fruits.next(), Some(&"banana"));
assert_eq!(my_iterable_fav_fruits.next(), Some(&"custard apple")); // TODO: Step 2
assert_eq!(my_iterable_fav_fruits.next(), Some(&"avocado"));
assert_eq!(my_iterable_fav_fruits.next(), Some(&"peach")); // TODO: Step 3
assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry"));
assert_eq!(my_iterable_fav_fruits.next(), None); // TODO: Step 4
}
// iterators2.rs
// Step 1.
// Complete the `capitalize_first` function.
// "hello" -> "Hello"
pub fn capitalize_first(input: &str) -> String {
let mut c = input.chars();
match c.next() {
None => String::new(),
Some(first) => {
first.to_uppercase().to_string() + &c.collect::<String>()
},
}
}
// Step 2.
// Apply the `capitalize_first` function to a slice of string slices.
// Return a vector of strings.
// ["hello", "world"] -> ["Hello", "World"]
pub fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
let mut res = vec![];
let mut iterator = words.into_iter();
while let Some(temp) = iterator.next(){
res.push(capitalize_first(temp));
}
res
}
// Step 3.
// Apply the `capitalize_first` function again to a slice of string slices.
// Return a single string.
// ["hello", " ", "world"] -> "Hello World"
pub fn capitalize_words_string(words: &[&str]) -> String {
let mut res = String::new();
let mut iterator = words.into_iter();
while let Some(temp) = iterator.next(){
res += &capitalize_first(temp);
}
res
}
// iterators3.rs
#[derive(Debug, PartialEq, Eq)]
pub enum DivisionError {
NotDivisible(NotDivisibleError),
DivideByZero,
}
#[derive(Debug, PartialEq, Eq)]
pub struct NotDivisibleError {
dividend: i32,
divisor: i32,
}
// Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
// Otherwise, return a suitable error.
pub fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {
if b == 0 {
Err(DivisionError::DivideByZero)
} else if a % b == 0 {
Ok(a / b)
} else {
Err(DivisionError::NotDivisible(NotDivisibleError {
dividend: a,
divisor: b,
}))
}
}
// Complete the function and return a value of the correct type so the test
// passes.
// Desired output: Ok([1, 11, 1426, 3])
fn result_with_list() -> Result<Vec<i32>, DivisionError> {
let numbers = vec![27, 297, 38502, 81];
numbers.into_iter().map(|n| divide(n, 27)).collect()
}
// Complete the function and return a value of the correct type so the test
// passes.
// Desired output: [Ok(1), Ok(11), Ok(1426), Ok(3)]
fn list_of_results() -> Vec<Result<i32,DivisionError>> {
let numbers = vec![27, 297, 38502, 81];
numbers.into_iter().map(|n| divide(n, 27)).collect()
}
// iterators4.rs
pub fn factorial(num: u64) -> u64 {
(1..num + 1).product()
}
// iterators5.rs
fn count_iterator(map: &HashMap<String, Progress>, value: Progress) -> usize {
// map is a hashmap with String keys and Progress values.
// map = { "variables1": Complete, "from_str": None, ... }
let mut iterator = map.iter();
let mut count = 0;
while let Some((_, val)) = iterator.next() {
if val == &value {
count += 1;
}
}
count
}
fn count_collection_iterator(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
// collection is a slice of hashmaps.
// collection = [{ "variables1": Complete, "from_str": None, ... },
// { "variables2": Complete, ... }, ... ]
let mut count = 0;
let mut collection_iterator = collection.iter();
while let Some(map) = collection_iterator.next(){
let mut iterator = map.iter();
while let Some((_, val)) = iterator.next() {
if val == &value {
count += 1;
}
}
}
count
}
Box
// box1.rs
#[derive(PartialEq, Debug)]
pub enum List {
Cons(i32, Box<List>),
Nil,
}
pub fn create_empty_list() -> List {
List::Nil
}
pub fn create_non_empty_list() -> List {
List::Cons(0, Box::new(List::Nil))
}
Rc
//rc1.rs
fn main() {
let sun = Rc::new(Sun {});
println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference
let mercury = Planet::Mercury(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 2 references
mercury.details();
let venus = Planet::Venus(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 3 references
venus.details();
let earth = Planet::Earth(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 4 references
earth.details();
let mars = Planet::Mars(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 5 references
mars.details();
let jupiter = Planet::Jupiter(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 6 references
jupiter.details();
// TODO
let saturn = Planet::Saturn(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 7 references
saturn.details();
// TODO
let uranus = Planet::Uranus(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 8 references
uranus.details();
// TODO
let neptune = Planet::Neptune(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 9 references
neptune.details();
assert_eq!(Rc::strong_count(&sun), 9);
drop(neptune);
println!("reference count = {}", Rc::strong_count(&sun)); // 8 references
drop(uranus);
println!("reference count = {}", Rc::strong_count(&sun)); // 7 references
drop(saturn);
println!("reference count = {}", Rc::strong_count(&sun)); // 6 references
drop(jupiter);
println!("reference count = {}", Rc::strong_count(&sun)); // 5 references
drop(mars);
println!("reference count = {}", Rc::strong_count(&sun)); // 4 references
// TODO
drop(earth);
println!("reference count = {}", Rc::strong_count(&sun)); // 3 references
// TODO
drop(venus);
println!("reference count = {}", Rc::strong_count(&sun)); // 2 references
// TODO
drop(mercury);
println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference
assert_eq!(Rc::strong_count(&sun), 1);
}
Arc
// arc1.rs
#![forbid(unused_imports)] // Do not change this, (or the next) line.
use std::sync::Arc;
use std::thread;
fn main() {
let numbers: Vec<_> = (0..100u32).collect();
let shared_numbers = Arc::new(numbers);// TODO
let mut joinhandles = Vec::new();
for offset in 0..8 {
let child_numbers = Arc::clone(&shared_numbers);// TODO
joinhandles.push(thread::spawn(move || {
let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum();
println!("Sum of offset {} is {}", offset, sum);
}));
}
for handle in joinhandles.into_iter() {
handle.join().unwrap();
}
}
Cow
这里主要是看是否发生了写时复制和我们一开始是获得的是否是引用
Owned(发生写时复制) <= 引用 => Borrowed (未发生写时复制)
Owned(发生写时复制) <= 非引用 => Owned(未发生写时复制)
// cow1.rs
use std::borrow::Cow;
fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> {
for i in 0..input.len() {
let v = input[i];
if v < 0 {
// Clones into a vector if not already owned.
input.to_mut()[i] = -v;
}
}
input
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reference_mutation() -> Result<(), &'static str> {
// Clone occurs because `input` needs to be mutated.
let slice = [-1, 0, 1];
let mut input = Cow::from(&slice[..]);
match abs_all(&mut input) {
Cow::Owned(_) => Ok(()),
_ => Err("Expected owned value"),
}
}
#[test]
fn reference_no_mutation() -> Result<(), &'static str> {
// No clone occurs because `input` doesn't need to be mutated.
let slice = [0, 1, 2];
let mut input = Cow::from(&slice[..]);
match abs_all(&mut input) {
Cow::Borrowed(_) => Ok(()),
_ => Err("Expected borrowed value"),
// TODO
}
}
#[test]
fn owned_no_mutation() -> Result<(), &'static str> {
// We can also pass `slice` without `&` so Cow owns it directly. In this
// case no mutation occurs and thus also no clone, but the result is
// still owned because it was never borrowed or mutated.
let slice = vec![0, 1, 2];
let mut input = Cow::from(slice);
match abs_all(&mut input) {
// TODO
Cow::Owned(_) => Ok(()),
_ => Err("Expected owned value"),
}
}
#[test]
fn owned_mutation() -> Result<(), &'static str> {
// Of course this is also the case if a mutation does occur. In this
// case the call to `to_mut()` returns a reference to the same data as
// before.
let slice = vec![-1, 0, 1];
let mut input = Cow::from(slice);
match abs_all(&mut input) {
// TODO
Cow::Owned(_) => Ok(()),
_ => Err("Expected owned value"),
}
}
}
Thread
// threads1.rs
use std::thread;
use std::time::{Duration, Instant};
fn main() {
let mut handles = vec![];
for i in 0..10 {
handles.push(thread::spawn(move || {
let start = Instant::now();
thread::sleep(Duration::from_millis(250));
println!("thread {} is complete", i);
start.elapsed().as_millis()
}));
}
let mut results: Vec<u128> = vec![];
for handle in handles {
// TODO: a struct is returned from thread::spawn, can you use it?
results.push(handle.join().expect(""));
}
if results.len() != 10 {
panic!("Oh no! All the spawned threads did not finish!");
}
println!();
for (i, result) in results.into_iter().enumerate() {
println!("thread {} took {}ms", i, result);
}
}
// threads2.rs
use std::sync::{Arc,Mutex};
use std::thread;
use std::time::Duration;
struct JobStatus {
jobs_completed: u32,
}
fn main() {
let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));
let mut handles = vec![];
for _ in 0..10 {
let status_shared = Arc::clone(&status);
let handle = thread::spawn(move || {
thread::sleep(Duration::from_millis(250));
// TODO: You must take an action before you update a shared value
let mut status_shared = status_shared.lock().unwrap();
status_shared.jobs_completed += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
// TODO: Print the value of the JobStatus.jobs_completed. Did you notice
// anything interesting in the output? Do you have to 'join' on all the
// handles?
println!("jobs completed {}", status.lock().unwrap().jobs_completed);
}
}
// threads3.rs
fn send_tx(q: Queue, tx: mpsc::Sender<u32>) -> () {
let qc = Arc::new(q);
let qc1 = Arc::clone(&qc);
let qc2 = Arc::clone(&qc);
let tx2 = tx.clone();
thread::spawn(move || {
for val in &qc1.first_half {
println!("sending {:?}", val);
tx.send(*val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
thread::spawn(move || {
for val in &qc2.second_half {
println!("sending {:?}", val);
tx2.send(*val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
}
Macros
// macros1.rs
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
fn main() {
my_macro!();
}
// macros2.rs
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
fn main() {
my_macro!();
}
// macros3.rs
#[macro_use]
mod macros {
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
}
// macros4.rs
#[rustfmt::skip]
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
($val:expr) => {
println!("Look at this other macro: {}", $val);
};
}
Clippy
// clippy1.rs
use std::f32;
fn main() {
let pi = f32::consts::PI;
let radius = 5.00f32;
let area = pi * f32::powi(radius, 2);
println!(
"The area of a circle with radius {:.2} is {:.5}!",
radius, area
)
}
// clippy2.rs
fn main() {
let mut res = 42;
let option = Some(12);
if let Some(x) = option {
res += x;
}
println!("{}", res);
}
// clippy3.rs
use std::mem;
#[allow(unused_variables, unused_assignments,clippy::let_unit_value)]
fn main() {
let my_option: Option<()> = None;
// if my_option.is_some() {
// my_option.unwrap();
// }
let my_arr = &[
-1, -2, -3,
-4, -5, -6
];
println!("My array! Here it is: {:?}", my_arr);
let my_empty_vec = vec![1, 2, 3, 4, 5].resize(0, 5);
println!("This Vec is empty, see? {:?}", my_empty_vec);
let mut value_a = 45;
let mut value_b = 66;
// Let's swap these two!
// value_a = value_b;
// value_b = value_a;
mem::swap(&mut value_a,&mut value_b);
println!("value a: {}; value b: {}", value_a, value_b);
}
Conversions
// using_as.rs
fn average(values: &[f64]) -> f64 {
let total = values.iter().sum::<f64>();
total / values.len() as f64
}
// from_into.rs
impl From<&str> for Person {
fn from(s: &str) -> Person {
if s.is_empty() {
Person::default()
} else {
let parts: Vec<&str> = s.split(',').collect();
if parts.len() != 2 {
Person::default()
} else {
let name = parts[0].trim();
if name.is_empty() {
Person::default()
} else if let Ok(age) = parts[1].trim().parse::<usize>() {
Person{name: String::from(name), age}
} else {
Person::default()
}
}
}
}
}
// from_str.rs
impl FromStr for Person {
type Err = ParsePersonError;
fn from_str(s: &str) -> Result<Person, Self::Err> {
match s.is_empty() {
true => Err(ParsePersonError::Empty),
false => {
let parts: Vec<&str> = s.split(',').collect();
match parts.len() != 2 {
true => return Err(ParsePersonError::BadLen),
false => {
let name = parts[0].trim();
if name.is_empty() {
return Err(ParsePersonError::NoName)
}
let number = parts[1].parse();
if let Err(x) = number{
return Err(ParsePersonError::ParseInt(x))
}
Ok(Person{name:String::from(name), age:number.unwrap()})
}
}
}
}
}
}
// try_from_into.rs
// Tuple implementation
impl TryFrom<(i16, i16, i16)> for Color {
type Error = IntoColorError;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
for i in [tuple.0,tuple.1,tuple.2]{
if i<0 || i>255{
return Err(IntoColorError::IntConversion)
}
}
Ok(Color{red:tuple.0 as u8,green:tuple.1 as u8,blue:tuple.2 as u8})
}
}
// Array implementation
impl TryFrom<[i16; 3]> for Color {
type Error = IntoColorError;
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {
Color::try_from((arr[0],arr[1],arr[2]))
}
}
// Slice implementation
impl TryFrom<&[i16]> for Color {
type Error = IntoColorError;
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
if slice.len()!=3{
Err(IntoColorError::BadLen)
} else {
Color::try_from((slice[0],slice[1],slice[2]))
}
}
}
// as_ref_mut.rs
fn byte_counter<T:AsRef<str>>(arg: T) -> usize {
arg.as_ref().as_bytes().len()
}
// Obtain the number of characters (not bytes) in the given argument.
// TODO: Add the AsRef trait appropriately as a trait bound.
fn char_counter<T:AsRef<str>>(arg: T) -> usize {
arg.as_ref().chars().count()
}
// Squares a number using as_mut().
// TODO: Add the appropriate trait bound.
fn num_sq<T:AsMut<u32>>(arg: &mut T) {
// TODO: Implement the function body.
*arg.as_mut() *= *arg.as_mut()
}
License:
CC BY 4.0