diff --git a/exercises/algorithm/algorithm1.rs b/exercises/algorithm/algorithm1.rs index f7a99bf02..83337a982 100644 --- a/exercises/algorithm/algorithm1.rs +++ b/exercises/algorithm/algorithm1.rs @@ -2,7 +2,7 @@ single linked list merge This problem requires you to merge two ordered singly linked lists into one ordered singly linked list */ -// I AM NOT DONE + use std::fmt::{self, Display, Formatter}; use std::ptr::NonNull; @@ -35,7 +35,7 @@ impl Default for LinkedList { } } -impl LinkedList { +impl LinkedList{ pub fn new() -> Self { Self { length: 0, @@ -69,14 +69,35 @@ impl LinkedList { }, } } - pub fn merge(list_a:LinkedList,list_b:LinkedList) -> Self + pub fn merge(mut list_a:LinkedList,mut list_b:LinkedList) -> Self + where + T: Ord + Clone, { //TODO - Self { - length: 0, - start: None, - end: None, + let mut list = LinkedList::::new(); + let mut idx_list_a:i32 = 0; + let mut idx_list_b:i32 = 0; + while idx_list_aval_b{ + node_val = Some(val_b); + idx_list_b+=1; + }else{ + idx_list_a+=1; + } + }else{ + idx_list_a+=1; + }; + let val= node_val.unwrap(); + list.add((*val).clone()); } + list } } @@ -94,7 +115,7 @@ where impl Display for Node where - T: Display, + T: Display , { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self.next { diff --git a/exercises/algorithm/algorithm10.rs b/exercises/algorithm/algorithm10.rs index a2ad731d0..d49088d10 100644 --- a/exercises/algorithm/algorithm10.rs +++ b/exercises/algorithm/algorithm10.rs @@ -2,7 +2,6 @@ graph This problem requires you to implement a basic graph functio */ -// I AM NOT DONE use std::collections::{HashMap, HashSet}; use std::fmt; @@ -29,7 +28,24 @@ impl Graph for UndirectedGraph { &self.adjacency_table } fn add_edge(&mut self, edge: (&str, &str, i32)) { - //TODO + let (from, to, weight) = edge; + // 确保两个节点都存在于图中 + self.add_node(from); + self.add_node(to); + + let from_str = from.to_string(); + let to_str = to.to_string(); + + // 无向图需要添加双向边 + self.adjacency_table_mutable() + .get_mut(&from_str) + .unwrap() + .push((to_str.clone(), weight)); + + self.adjacency_table_mutable() + .get_mut(&to_str) + .unwrap() + .push((from_str, weight)); } } pub trait Graph { @@ -37,8 +53,15 @@ pub trait Graph { fn adjacency_table_mutable(&mut self) -> &mut HashMap>; fn adjacency_table(&self) -> &HashMap>; fn add_node(&mut self, node: &str) -> bool { - //TODO - true + let node_str = node.to_string(); + // 如果节点已存在,返回false + if self.adjacency_table().contains_key(&node_str) { + false + } else { + // 新增节点,邻接列表初始为空 + self.adjacency_table_mutable().insert(node_str, Vec::new()); + true + } } fn add_edge(&mut self, edge: (&str, &str, i32)) { //TODO diff --git a/exercises/algorithm/algorithm2.rs b/exercises/algorithm/algorithm2.rs index 08720ff44..51707eeb9 100644 --- a/exercises/algorithm/algorithm2.rs +++ b/exercises/algorithm/algorithm2.rs @@ -2,7 +2,7 @@ double linked list reverse This problem requires you to reverse a doubly linked list */ -// I AM NOT DONE + use std::fmt::{self, Display, Formatter}; use std::ptr::NonNull; @@ -73,7 +73,20 @@ impl LinkedList { } } pub fn reverse(&mut self){ - // TODO + //// 当地反转双向链表 + // 交换头指针和尾指针 + std::mem::swap(&mut self.start, &mut self.end); + + let mut current = self.start; + while let Some(mut curr_ptr) = current { + // 交换当前节点的prev和next指针 + unsafe { + std::mem::swap(&mut (*curr_ptr.as_ptr()).prev, &mut (*curr_ptr.as_ptr()).next); + // 移动到下一个节点(原prev指针) + current = (*curr_ptr.as_ptr()).next; + } + } + } } diff --git a/exercises/algorithm/algorithm3.rs b/exercises/algorithm/algorithm3.rs index 37878d6a7..caec49daf 100644 --- a/exercises/algorithm/algorithm3.rs +++ b/exercises/algorithm/algorithm3.rs @@ -3,10 +3,23 @@ This problem requires you to implement a sorting algorithm you can use bubble sorting, insertion sorting, heap sorting, etc. */ -// I AM NOT DONE -fn sort(array: &mut [T]){ +use std::ops::Deref; +use std::fmt::Display; + +fn sort(array: &mut [T]) +where T: Ord +Display+ std::fmt::Debug { //TODO + let size = array.len(); + println!("{size}"); + for i in 1..size{ + let mut j = i; + while j>0&&array[j-1]>array[j] { + array.swap(j, j-1); + j-=1; + } + } + } #[cfg(test)] mod tests { diff --git a/exercises/algorithm/algorithm4.rs b/exercises/algorithm/algorithm4.rs index 271b772c5..31f93ddc1 100644 --- a/exercises/algorithm/algorithm4.rs +++ b/exercises/algorithm/algorithm4.rs @@ -3,7 +3,7 @@ This problem requires you to implement a basic interface for a binary tree */ -//I AM NOT DONE + use std::cmp::Ordering; use std::fmt::Debug; @@ -50,23 +50,56 @@ where // Insert a value into the BST fn insert(&mut self, value: T) { - //TODO + if let Some(ref mut root_node) = self.root { + root_node.insert(value); + } else { + // 根节点为空时直接创建新节点 + self.root = Some(Box::new(TreeNode::new(value))); + } } // Search for a value in the BST fn search(&self, value: T) -> bool { //TODO - true + self.root.as_ref().map_or(false, |node| node.search(&value)) } } impl TreeNode where - T: Ord, + T: Ord+PartialEq, { // Insert a node into the tree fn insert(&mut self, value: T) { //TODO + match self.value.cmp(&value) { + Ordering::Greater => { + // 插入到左子树 + if let Some(ref mut left_child) = self.left { + left_child.insert(value); + } else { + self.left = Some(Box::new(TreeNode::new(value))); + } + } + Ordering::Less => { + // 插入到右子树 + if let Some(ref mut right_child) = self.right { + right_child.insert(value); + } else { + self.right = Some(Box::new(TreeNode::new(value))); + } + } + Ordering::Equal => { + // 相等的值不插入(BST通常不存储重复值) + } + } + } + fn search(&self, value: &T) -> bool { + match self.value.cmp(value) { + Ordering::Equal => true, + Ordering::Greater => self.left.as_ref().map_or(false, |node| node.search(value)), + Ordering::Less => self.right.as_ref().map_or(false, |node| node.search(value)), + } } } diff --git a/exercises/algorithm/algorithm5.rs b/exercises/algorithm/algorithm5.rs index 8f206d1a9..f5f680ebd 100644 --- a/exercises/algorithm/algorithm5.rs +++ b/exercises/algorithm/algorithm5.rs @@ -3,7 +3,7 @@ This problem requires you to implement a basic BFS algorithm */ -//I AM NOT DONE + use std::collections::VecDeque; // Define a graph @@ -29,8 +29,22 @@ impl Graph { fn bfs_with_return(&self, start: usize) -> Vec { //TODO - + let n = self.adj.len(); + let mut i = 0; let mut visit_order = vec![]; + let mut visited = vec![0;n]; + visit_order.push(start); + visited[start] = 1; + while i, visit_order: &mut Vec) { //TODO + if visited.contains(&v) { + return (); + } + visited.insert(v.clone()); + visit_order.push(v.clone()); + for idx in self.adj[v].iter(){ + self.dfs_util(*idx,visited,visit_order); + } } // Perform a depth-first search on the graph, return the order of visited nodes diff --git a/exercises/algorithm/algorithm7.rs b/exercises/algorithm/algorithm7.rs index e0c3a5ab2..fa65a02a8 100644 --- a/exercises/algorithm/algorithm7.rs +++ b/exercises/algorithm/algorithm7.rs @@ -3,7 +3,6 @@ This question requires you to use a stack to achieve a bracket match */ -// I AM NOT DONE #[derive(Debug)] struct Stack { size: usize, @@ -32,7 +31,11 @@ impl Stack { } fn pop(&mut self) -> Option { // TODO - None + if self.size ==0{ + return None; + } + self.size -= 1; + Some(self.data.pop()?) } fn peek(&self) -> Option<&T> { if 0 == self.size { @@ -73,7 +76,8 @@ impl Iterator for IntoIter { type Item = T; fn next(&mut self) -> Option { if !self.0.is_empty() { - self.0.size -= 1;self.0.data.pop() + self.0.size -= 1; + self.0.data.pop() } else { None @@ -101,8 +105,37 @@ impl<'a, T> Iterator for IterMut<'a, T> { fn bracket_match(bracket: &str) -> bool { - //TODO - true + //TODO + + let mut stack = Stack::new(); + + for c in bracket.chars() { + match c { + // 遇到左括号则入栈 + '(' | '{' | '[' => stack.push(c), + // 遇到右括号则检查匹配 + ')' => { + if stack.pop() != Some('(') { + return false; + } + } + '}' => { + if stack.pop() != Some('{') { + return false; + } + } + ']' => { + if stack.pop() != Some('[') { + return false; + } + } + // 忽略其他字符 + _ => (), + } + } + + // 所有括号处理完毕后,栈必须为空才是完全匹配 + stack.is_empty() } #[cfg(test)] diff --git a/exercises/algorithm/algorithm8.rs b/exercises/algorithm/algorithm8.rs index d1d183b84..d7f69ef0e 100644 --- a/exercises/algorithm/algorithm8.rs +++ b/exercises/algorithm/algorithm8.rs @@ -2,7 +2,7 @@ queue This question requires you to use queues to implement the functionality of the stac */ -// I AM NOT DONE + #[derive(Debug)] pub struct Queue { @@ -67,15 +67,38 @@ impl myStack { } } pub fn push(&mut self, elem: T) { + if !self.q1.is_empty() { + self.q1.enqueue(elem); + } else { + self.q2.enqueue(elem); + } //TODO } pub fn pop(&mut self) -> Result { - //TODO - Err("Stack is empty") + if self.is_empty() { + return Err("Stack is empty"); + } + + // 确定源队列(有元素)和目标队列(空) + let (src, dst) = if !self.q1.is_empty() { + (&mut self.q1, &mut self.q2) + } else { + (&mut self.q2, &mut self.q1) + }; + + // 将源队列中除最后一个元素外的所有元素移到目标队列 + let src_size = src.size(); + for _ in 0..src_size - 1 { + let elem = src.dequeue().unwrap(); + dst.enqueue(elem); + } + + // 弹出源队列中剩余的最后一个元素(即栈顶元素) + src.dequeue() } pub fn is_empty(&self) -> bool { //TODO - true + self.q1.is_empty() && self.q2.is_empty() } } diff --git a/exercises/algorithm/algorithm9.rs b/exercises/algorithm/algorithm9.rs index 6c8021a4d..2610b2236 100644 --- a/exercises/algorithm/algorithm9.rs +++ b/exercises/algorithm/algorithm9.rs @@ -2,7 +2,7 @@ heap This question requires you to implement a binary heap function */ -// I AM NOT DONE + use std::cmp::Ord; use std::default::Default; @@ -37,6 +37,24 @@ where } pub fn add(&mut self, value: T) { + self.count += 1; + // 确保有足够空间,索引从1开始 + if self.count >= self.items.len() { + self.items.push(value); + } else { + self.items[self.count] = value; + } + // 上浮操作:将新元素放到正确位置 + let mut current = self.count; + while current > 1 { + let parent = self.parent_idx(current); + if (self.comparator)(&self.items[current], &self.items[parent]) { + self.items.swap(current, parent); + current = parent; + } else { + break; + } + } //TODO } @@ -57,8 +75,21 @@ where } fn smallest_child_idx(&self, idx: usize) -> usize { - //TODO - 0 + let left = self.left_child_idx(idx); + let right = self.right_child_idx(idx); + + // 检查右子节点是否存在 + if right > self.count { + left + } else { + // 根据比较器选择符合条件的子节点 + if (self.comparator)(&self.items[left], &self.items[right]) { + left + } else { + right + } + } + } } @@ -84,8 +115,31 @@ where type Item = T; fn next(&mut self) -> Option { - //TODO - None + if self.is_empty() { + return None; + } + + // 取出堆顶元素 + let top = std::mem::take(&mut self.items[1]); + // 将最后一个元素移到堆顶 + if self.count > 1 { + self.items[1] = std::mem::take(&mut self.items[self.count]); + } + self.count -= 1; + + // 下沉操作:维护堆特性 + let mut current = 1; + while self.children_present(current) { + let child = self.smallest_child_idx(current); + if (self.comparator)(&self.items[child], &self.items[current]) { + self.items.swap(current, child); + current = child; + } else { + break; + } + } + + Some(top) } } diff --git a/exercises/clippy/clippy1.rs b/exercises/clippy/clippy1.rs index 95c0141f4..3b01ad5c3 100644 --- a/exercises/clippy/clippy1.rs +++ b/exercises/clippy/clippy1.rs @@ -9,12 +9,12 @@ // Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + use std::f32; fn main() { - let pi = 3.14f32; + let pi = f32::consts::PI; let radius = 5.00f32; let area = pi * f32::powi(radius, 2); diff --git a/exercises/clippy/clippy2.rs b/exercises/clippy/clippy2.rs index 9b87a0b70..3250cad51 100644 --- a/exercises/clippy/clippy2.rs +++ b/exercises/clippy/clippy2.rs @@ -3,12 +3,12 @@ // Execute `rustlings hint clippy2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + fn main() { let mut res = 42; let option = Some(12); - for x in option { + if let Some(x) = option { res += x; } println!("{}", res); diff --git a/exercises/clippy/clippy3.rs b/exercises/clippy/clippy3.rs index 35021f841..72dff5c0e 100644 --- a/exercises/clippy/clippy3.rs +++ b/exercises/clippy/clippy3.rs @@ -4,28 +4,30 @@ // // Execute `rustlings hint clippy3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE + #[allow(unused_variables, unused_assignments)] fn main() { let my_option: Option<()> = None; - if my_option.is_none() { - my_option.unwrap(); - } + // if my_option.is_none() { + // my_option.unwrap(); + // } let my_arr = &[ - -1, -2, -3 + -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); + let mut my_empty_vec = vec![1, 2, 3, 4, 5]; + my_empty_vec.clear(); 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; + // value_a = value_b; + // value_b = value_a; + std::mem::swap(&mut value_a, &mut value_b); println!("value a: {}; value b: {}", value_a, value_b); } diff --git a/exercises/conversions/as_ref_mut.rs b/exercises/conversions/as_ref_mut.rs index 626a36c45..ba614776f 100644 --- a/exercises/conversions/as_ref_mut.rs +++ b/exercises/conversions/as_ref_mut.rs @@ -7,25 +7,26 @@ // Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + // Obtain the number of bytes (not characters) in the given argument. // TODO: Add the AsRef trait appropriately as a trait bound. -fn byte_counter(arg: T) -> usize { +fn byte_counter>(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(arg: T) -> usize { +fn char_counter>(arg: T) -> usize { arg.as_ref().chars().count() } // Squares a number using as_mut(). // TODO: Add the appropriate trait bound. -fn num_sq(arg: &mut T) { +fn num_sq>(mut arg:T) { // TODO: Implement the function body. - ??? + let num =*(arg).as_mut(); + *(arg.as_mut()) = num*num; } #[cfg(test)] diff --git a/exercises/conversions/from_into.rs b/exercises/conversions/from_into.rs index aba471d92..79d5cc9ea 100644 --- a/exercises/conversions/from_into.rs +++ b/exercises/conversions/from_into.rs @@ -40,10 +40,20 @@ impl Default for Person { // If while parsing the age, something goes wrong, then return the default of // Person Otherwise, then return an instantiated Person object with the results -// I AM NOT DONE - +use std::str::FromStr; impl From<&str> for Person { fn from(s: &str) -> Person { + let words: Vec<&str>=s.split(',').collect(); + let mut rtn = Person::default(); + if words.len() < 2||words[0].len() ==0|| words.len() > 2 { + return rtn; + } + match u8::from_str(words[1]){ + Ok(num) => rtn.age = num as usize, + Err(e) => return rtn, + } + rtn.name = words[0].to_string(); + rtn } } diff --git a/exercises/conversions/from_str.rs b/exercises/conversions/from_str.rs index 34472c32c..8068b3aea 100644 --- a/exercises/conversions/from_str.rs +++ b/exercises/conversions/from_str.rs @@ -31,7 +31,7 @@ enum ParsePersonError { ParseInt(ParseIntError), } -// I AM NOT DONE + // Steps: // 1. If the length of the provided string is 0, an error should be returned @@ -52,6 +52,25 @@ enum ParsePersonError { impl FromStr for Person { type Err = ParsePersonError; fn from_str(s: &str) -> Result { + let words: Vec<&str>=s.split(',').collect(); + let mut age:u8 = 0; + if s.len() == 0 { + return Err(ParsePersonError::Empty); + } + if words.len() < 2|| words.len() > 2 { + return Err(ParsePersonError::BadLen); + } + if words[0].len() ==0{ + return Err(ParsePersonError::NoName); + } + match u8::from_str(words[1]){ + Ok(num) => age = num, + Err(e) => return Err(ParsePersonError::ParseInt(e)), + } + Ok(Person{ + name:words[0].to_string(), + age:age as usize + }) } } diff --git a/exercises/conversions/try_from_into.rs b/exercises/conversions/try_from_into.rs index 32d6ef39e..d03c1743d 100644 --- a/exercises/conversions/try_from_into.rs +++ b/exercises/conversions/try_from_into.rs @@ -27,7 +27,7 @@ enum IntoColorError { IntConversion, } -// I AM NOT DONE + // Your task is to complete this implementation and return an Ok result of inner // type Color. You need to create an implementation for a tuple of three @@ -41,6 +41,17 @@ enum IntoColorError { impl TryFrom<(i16, i16, i16)> for Color { type Error = IntoColorError; fn try_from(tuple: (i16, i16, i16)) -> Result { + let (a,b,c) = tuple; + if a<0 ||a >255 || b<0 ||b>255 ||c<0 ||c >255 { + return Err(IntoColorError::IntConversion); + } + Ok( + Color{ + red:a as u8, + green:b as u8, + blue:c as u8 + } + ) } } @@ -48,6 +59,17 @@ impl TryFrom<(i16, i16, i16)> for Color { impl TryFrom<[i16; 3]> for Color { type Error = IntoColorError; fn try_from(arr: [i16; 3]) -> Result { + if arr[0]<0 ||arr[0] >255 || arr[1]<0 ||arr[1]>255 ||arr[2]<0 ||arr[2] >255 { + return Err(IntoColorError::IntConversion); + } + + Ok( + Color{ + red:arr[0] as u8, + green:arr[1] as u8, + blue:arr[2] as u8 + } + ) } } @@ -55,6 +77,19 @@ impl TryFrom<[i16; 3]> for Color { impl TryFrom<&[i16]> for Color { type Error = IntoColorError; fn try_from(slice: &[i16]) -> Result { + if slice.len()!=3{ + return Err(IntoColorError::BadLen); + } + if slice[0]<0 ||slice[0] >255 || slice[1]<0 ||slice[1]>255 ||slice[2]<0 ||slice[2] >255 { + return Err(IntoColorError::IntConversion); + } + Ok( + Color{ + red:slice[0] as u8, + green:slice[1] as u8, + blue:slice[2] as u8 + } + ) } } diff --git a/exercises/conversions/using_as.rs b/exercises/conversions/using_as.rs index 414cef3a0..f4adc9c8e 100644 --- a/exercises/conversions/using_as.rs +++ b/exercises/conversions/using_as.rs @@ -10,11 +10,11 @@ // Execute `rustlings hint using_as` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + fn average(values: &[f64]) -> f64 { let total = values.iter().sum::(); - total / values.len() + total / values.len() as f64 } fn main() { diff --git a/exercises/enums/enums1.rs b/exercises/enums/enums1.rs index 25525b252..083352b03 100644 --- a/exercises/enums/enums1.rs +++ b/exercises/enums/enums1.rs @@ -2,11 +2,14 @@ // // No hints this time! ;) -// I AM NOT DONE #[derive(Debug)] enum Message { // TODO: define a few types of messages as used below + Quit, + Echo, + Move, + ChangeColor } fn main() { diff --git a/exercises/enums/enums2.rs b/exercises/enums/enums2.rs index df93fe0f1..db824b1d4 100644 --- a/exercises/enums/enums2.rs +++ b/exercises/enums/enums2.rs @@ -3,11 +3,14 @@ // Execute `rustlings hint enums2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE #[derive(Debug)] enum Message { // TODO: define the different variants used below + Move{x:i32,y:i32}, + Echo(String), + ChangeColor(i32,i32,i32), + Quit } impl Message { diff --git a/exercises/enums/enums3.rs b/exercises/enums/enums3.rs index 5d284417e..85d911289 100644 --- a/exercises/enums/enums3.rs +++ b/exercises/enums/enums3.rs @@ -5,10 +5,13 @@ // Execute `rustlings hint enums3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE enum Message { // TODO: implement the message variant types based on their usage below + Move(Point), + Echo(String), + ChangeColor(u8,u8,u8), + Quit } struct Point { @@ -43,6 +46,20 @@ impl State { // 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(point) =>{ + self.position = point; + }, + Message::Echo(str) =>{ + self.message = str.clone(); + }, + Message::ChangeColor(i,j,k) => { + self.color = (i,j,k); + }, + Message::Quit =>{ + self.quit = true; + } + } } } diff --git a/exercises/error_handling/errors1.rs b/exercises/error_handling/errors1.rs index 13d2724cb..25f83d8c8 100644 --- a/exercises/error_handling/errors1.rs +++ b/exercises/error_handling/errors1.rs @@ -9,14 +9,14 @@ // 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 { + +pub fn generate_nametag_text(name: String) -> Result { if name.is_empty() { // Empty names aren't allowed. - None + Err("`name` was empty; it must be nonempty.".into()) } else { - Some(format!("Hi! My name is {}", name)) + Ok(format!("Hi! My name is {}", name)) } } diff --git a/exercises/error_handling/errors2.rs b/exercises/error_handling/errors2.rs index d86f326d0..85738d72a 100644 --- a/exercises/error_handling/errors2.rs +++ b/exercises/error_handling/errors2.rs @@ -19,14 +19,14 @@ // Execute `rustlings hint errors2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + use std::num::ParseIntError; pub fn total_cost(item_quantity: &str) -> Result { let processing_fee = 1; let cost_per_item = 5; - let qty = item_quantity.parse::(); + let qty = item_quantity.parse::()?; Ok(qty * cost_per_item + processing_fee) } diff --git a/exercises/error_handling/errors3.rs b/exercises/error_handling/errors3.rs index d42d3b17c..af111e26b 100644 --- a/exercises/error_handling/errors3.rs +++ b/exercises/error_handling/errors3.rs @@ -7,11 +7,11 @@ // Execute `rustlings hint errors3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + use std::num::ParseIntError; -fn main() { +fn main() -> Result<(), ParseIntError>{ let mut tokens = 100; let pretend_user_input = "8"; @@ -23,6 +23,7 @@ fn main() { tokens -= cost; println!("You now have {} tokens.", tokens); } + Ok(()) } pub fn total_cost(item_quantity: &str) -> Result { diff --git a/exercises/error_handling/errors4.rs b/exercises/error_handling/errors4.rs index e04bff77a..85128b123 100644 --- a/exercises/error_handling/errors4.rs +++ b/exercises/error_handling/errors4.rs @@ -3,7 +3,6 @@ // Execute `rustlings hint errors4` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE #[derive(PartialEq, Debug)] struct PositiveNonzeroInteger(u64); @@ -17,6 +16,11 @@ enum CreationError { impl PositiveNonzeroInteger { fn new(value: i64) -> Result { // Hmm...? Why is this only returning an Ok value? + if value<0 { + return Err(CreationError::Negative); + }else if value ==0 { + return Err(CreationError::Zero); + }; Ok(PositiveNonzeroInteger(value as u64)) } } diff --git a/exercises/error_handling/errors5.rs b/exercises/error_handling/errors5.rs index 92461a7e0..3954dbe88 100644 --- a/exercises/error_handling/errors5.rs +++ b/exercises/error_handling/errors5.rs @@ -22,14 +22,13 @@ // Execute `rustlings hint errors5` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE 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> { +fn main() -> Result<(), Box> { let pretend_user_input = "42"; let x: i64 = pretend_user_input.parse()?; println!("output={:?}", PositiveNonzeroInteger::new(x)?); diff --git a/exercises/error_handling/errors6.rs b/exercises/error_handling/errors6.rs index aaf0948ef..506154b38 100644 --- a/exercises/error_handling/errors6.rs +++ b/exercises/error_handling/errors6.rs @@ -9,7 +9,7 @@ // Execute `rustlings hint errors6` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + use std::num::ParseIntError; @@ -26,13 +26,16 @@ impl ParsePosNonzeroError { } // TODO: add another error conversion function here. // fn from_parseint... + fn from_parseint(err: ParseIntError) ->ParsePosNonzeroError{ + ParsePosNonzeroError::ParseInt(err) + } } fn parse_pos_nonzero(s: &str) -> Result { // TODO: change this to return an appropriate error instead of panicking // when `parse()` returns an error. - let x: i64 = s.parse().unwrap(); - PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation) + let x: i64 = s.parse().map_err(|e: ParseIntError| ParsePosNonzeroError::from_parseint(e))?; + PositiveNonzeroInteger::new(x).map_err(|e| ParsePosNonzeroError::from_creation(e)) } // Don't change anything below this line. diff --git a/exercises/generics/generics1.rs b/exercises/generics/generics1.rs index 35c1d2fee..2321f732d 100644 --- a/exercises/generics/generics1.rs +++ b/exercises/generics/generics1.rs @@ -6,9 +6,9 @@ // Execute `rustlings hint generics1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + fn main() { - let mut shopping_list: Vec = Vec::new(); + let mut shopping_list: Vec<&str> = Vec::new(); shopping_list.push("milk"); } diff --git a/exercises/generics/generics2.rs b/exercises/generics/generics2.rs index 074cd938c..ae12d35da 100644 --- a/exercises/generics/generics2.rs +++ b/exercises/generics/generics2.rs @@ -6,14 +6,14 @@ // Execute `rustlings hint generics2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE -struct Wrapper { - value: u32, + +struct Wrapper { + value: T, } -impl Wrapper { - pub fn new(value: u32) -> Self { +impl Wrapper { + pub fn new(value: T) -> Self { Wrapper { value } } } diff --git a/exercises/hashmaps/hashmaps1.rs b/exercises/hashmaps/hashmaps1.rs index 80829eaa6..e0db75e9b 100644 --- a/exercises/hashmaps/hashmaps1.rs +++ b/exercises/hashmaps/hashmaps1.rs @@ -11,17 +11,19 @@ // Execute `rustlings hint hashmaps1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE use std::collections::HashMap; fn fruit_basket() -> HashMap { - let mut basket = // TODO: declare your hash map here. + let mut basket = HashMap::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("banana1"), 2); + + basket.insert(String::from("banana2"), 2); basket } diff --git a/exercises/hashmaps/hashmaps2.rs b/exercises/hashmaps/hashmaps2.rs index a59256909..1a28425ba 100644 --- a/exercises/hashmaps/hashmaps2.rs +++ b/exercises/hashmaps/hashmaps2.rs @@ -14,7 +14,6 @@ // Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE use std::collections::HashMap; @@ -40,6 +39,9 @@ fn fruit_basket(basket: &mut HashMap) { // 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,1); + }; } } diff --git a/exercises/hashmaps/hashmaps3.rs b/exercises/hashmaps/hashmaps3.rs index 08e977c33..5ed59c24e 100644 --- a/exercises/hashmaps/hashmaps3.rs +++ b/exercises/hashmaps/hashmaps3.rs @@ -14,7 +14,6 @@ // Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE use std::collections::HashMap; @@ -39,6 +38,20 @@ fn build_scores_table(results: String) -> HashMap { // 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. + if !scores.contains_key(&team_1_name) { + scores.insert(team_1_name.clone(),Team{goals_scored:0,goals_conceded:0}); + } + if !scores.contains_key(&team_2_name) { + scores.insert(team_2_name.clone(),Team{goals_scored:0,goals_conceded:0}); + } + if let Some(team) = scores.get_mut(&team_1_name){ + team.goals_scored += team_1_score; + team.goals_conceded += team_2_score; + } + if let Some(team) = scores.get_mut(&team_2_name){ + team.goals_scored += team_2_score; + team.goals_conceded += team_1_score; + } } scores } diff --git a/exercises/iterators/iterators1.rs b/exercises/iterators/iterators1.rs index b3f698be3..a80245d1a 100644 --- a/exercises/iterators/iterators1.rs +++ b/exercises/iterators/iterators1.rs @@ -9,17 +9,17 @@ // Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + fn main() { let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"]; - let mut my_iterable_fav_fruits = ???; // TODO: Step 1 + let mut my_iterable_fav_fruits = my_fav_fruits.into_iter(); // TODO: Step 1 - assert_eq!(my_iterable_fav_fruits.next(), Some(&"banana")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 2 - assert_eq!(my_iterable_fav_fruits.next(), Some(&"avocado")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 3 - assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 4 + 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 } diff --git a/exercises/iterators/iterators2.rs b/exercises/iterators/iterators2.rs index dda82a085..39edb1e49 100644 --- a/exercises/iterators/iterators2.rs +++ b/exercises/iterators/iterators2.rs @@ -6,7 +6,6 @@ // Execute `rustlings hint iterators2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE // Step 1. // Complete the `capitalize_first` function. @@ -15,7 +14,7 @@ pub fn capitalize_first(input: &str) -> String { let mut c = input.chars(); match c.next() { None => String::new(), - Some(first) => ???, + Some(first) => first.to_string().to_uppercase() + &input[1..] } } @@ -24,7 +23,7 @@ pub fn capitalize_first(input: &str) -> String { // Return a vector of strings. // ["hello", "world"] -> ["Hello", "World"] pub fn capitalize_words_vector(words: &[&str]) -> Vec { - vec![] + words.into_iter().map(|s| capitalize_first(s)).collect() } // Step 3. @@ -32,7 +31,7 @@ pub fn capitalize_words_vector(words: &[&str]) -> Vec { // Return a single string. // ["hello", " ", "world"] -> "Hello World" pub fn capitalize_words_string(words: &[&str]) -> String { - String::new() + words.into_iter().map(|s| capitalize_first(s)).collect() } #[cfg(test)] diff --git a/exercises/iterators/iterators3.rs b/exercises/iterators/iterators3.rs index 29fa23a3e..f1574704e 100644 --- a/exercises/iterators/iterators3.rs +++ b/exercises/iterators/iterators3.rs @@ -9,7 +9,7 @@ // Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + #[derive(Debug, PartialEq, Eq)] pub enum DivisionError { @@ -26,23 +26,31 @@ pub struct NotDivisibleError { // 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 { - todo!(); + 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() -> () { +fn result_with_list() -> Result, DivisionError>{ let numbers = vec![27, 297, 38502, 81]; - let division_results = numbers.into_iter().map(|n| divide(n, 27)); + let division_results = numbers.into_iter().map(|n| divide(n, 27)).collect(); + division_results } // 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() -> () { +fn list_of_results() -> Vec> { let numbers = vec![27, 297, 38502, 81]; - let division_results = numbers.into_iter().map(|n| divide(n, 27)); + let division_results = numbers.into_iter().map(|n| divide(n, 27)).collect(); + division_results } #[cfg(test)] diff --git a/exercises/iterators/iterators4.rs b/exercises/iterators/iterators4.rs index 79e1692ba..8ac8813cb 100644 --- a/exercises/iterators/iterators4.rs +++ b/exercises/iterators/iterators4.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + pub fn factorial(num: u64) -> u64 { // Complete this function to return the factorial of num @@ -15,6 +15,7 @@ pub fn factorial(num: u64) -> u64 { // For an extra challenge, don't use: // - recursion // Execute `rustlings hint iterators4` for hints. + (1..num+1).product() } #[cfg(test)] diff --git a/exercises/iterators/iterators5.rs b/exercises/iterators/iterators5.rs index a062ee4c7..444c74d19 100644 --- a/exercises/iterators/iterators5.rs +++ b/exercises/iterators/iterators5.rs @@ -11,7 +11,6 @@ // Execute `rustlings hint iterators5` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE use std::collections::HashMap; @@ -35,7 +34,13 @@ fn count_for(map: &HashMap, value: Progress) -> usize { fn count_iterator(map: &HashMap, value: Progress) -> usize { // map is a hashmap with String keys and Progress values. // map = { "variables1": Complete, "from_str": None, ... } - todo!(); + // let mut count = 0; + // for (key,val) in map.iter(){ + // if *val == value { + // count += 1; + // } + // } + map.into_iter().filter(|(key,val)| **val==value).count() } fn count_collection_for(collection: &[HashMap], value: Progress) -> usize { @@ -54,7 +59,10 @@ fn count_collection_iterator(collection: &[HashMap], value: Pr // collection is a slice of hashmaps. // collection = [{ "variables1": Complete, "from_str": None, ... }, // { "variables2": Complete, ... }, ... ] - todo!(); + collection.into_iter() + .flat_map(|x| x.values()) + .filter(|&progress| *progress == value) + .count() } #[cfg(test)] diff --git a/exercises/lifetimes/lifetimes1.rs b/exercises/lifetimes/lifetimes1.rs index 87bde490c..b40fc1c95 100644 --- a/exercises/lifetimes/lifetimes1.rs +++ b/exercises/lifetimes/lifetimes1.rs @@ -8,9 +8,9 @@ // Execute `rustlings hint lifetimes1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE -fn longest(x: &str, y: &str) -> &str { + +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { diff --git a/exercises/lifetimes/lifetimes2.rs b/exercises/lifetimes/lifetimes2.rs index 4f3d8c185..f228a25a8 100644 --- a/exercises/lifetimes/lifetimes2.rs +++ b/exercises/lifetimes/lifetimes2.rs @@ -6,7 +6,7 @@ // Execute `rustlings hint lifetimes2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { @@ -23,5 +23,5 @@ fn main() { let string2 = String::from("xyz"); result = longest(string1.as_str(), string2.as_str()); } - println!("The longest string is '{}'", result); + //println!("The longest string is '{}'", result); } diff --git a/exercises/lifetimes/lifetimes3.rs b/exercises/lifetimes/lifetimes3.rs index 9c59f9c02..249ecb288 100644 --- a/exercises/lifetimes/lifetimes3.rs +++ b/exercises/lifetimes/lifetimes3.rs @@ -5,11 +5,11 @@ // Execute `rustlings hint lifetimes3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE -struct Book { - author: &str, - title: &str, + +struct Book <'a>{ + author: &'a str, + title: &'a str, } fn main() { diff --git a/exercises/macros/macros1.rs b/exercises/macros/macros1.rs index 678de6eec..eb0cbbaa8 100644 --- a/exercises/macros/macros1.rs +++ b/exercises/macros/macros1.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint macros1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + macro_rules! my_macro { () => { @@ -12,5 +12,5 @@ macro_rules! my_macro { } fn main() { - my_macro(); + my_macro!(); } diff --git a/exercises/macros/macros2.rs b/exercises/macros/macros2.rs index 788fc16a9..a72d904d7 100644 --- a/exercises/macros/macros2.rs +++ b/exercises/macros/macros2.rs @@ -3,14 +3,17 @@ // Execute `rustlings hint macros2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE -fn main() { - my_macro!(); -} + + macro_rules! my_macro { () => { println!("Check out my macro!"); }; } + + +fn main() { + my_macro!(); +} diff --git a/exercises/macros/macros3.rs b/exercises/macros/macros3.rs index b795c1493..5ecaa239b 100644 --- a/exercises/macros/macros3.rs +++ b/exercises/macros/macros3.rs @@ -5,16 +5,18 @@ // Execute `rustlings hint macros3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + mod macros { macro_rules! my_macro { () => { println!("Check out my macro!"); }; + } + pub(crate) use my_macro; } fn main() { - my_macro!(); + macros::my_macro!(); } diff --git a/exercises/macros/macros4.rs b/exercises/macros/macros4.rs index 71b45a095..59b9ee457 100644 --- a/exercises/macros/macros4.rs +++ b/exercises/macros/macros4.rs @@ -3,13 +3,13 @@ // Execute `rustlings hint macros4` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + #[rustfmt::skip] macro_rules! my_macro { () => { println!("Check out my macro!"); - } + }; ($val:expr) => { println!("Look at this other macro: {}", $val); } diff --git a/exercises/modules/modules1.rs b/exercises/modules/modules1.rs index 9eb5a48b7..94308b5c5 100644 --- a/exercises/modules/modules1.rs +++ b/exercises/modules/modules1.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint modules1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + mod sausage_factory { // Don't let anybody outside of this module see this! @@ -11,7 +11,7 @@ mod sausage_factory { String::from("Ginger") } - fn make_sausage() { + pub fn make_sausage() { get_secret_recipe(); println!("sausage!"); } diff --git a/exercises/modules/modules2.rs b/exercises/modules/modules2.rs index 041545431..47a5bbdc0 100644 --- a/exercises/modules/modules2.rs +++ b/exercises/modules/modules2.rs @@ -7,12 +7,11 @@ // Execute `rustlings hint modules2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE mod delicious_snacks { // TODO: Fix these use statements - use self::fruits::PEAR as ??? - use self::veggies::CUCUMBER as ??? + pub use self::fruits::PEAR as fruit; + pub use self::veggies::CUCUMBER as veggie; mod fruits { pub const PEAR: &'static str = "Pear"; diff --git a/exercises/modules/modules3.rs b/exercises/modules/modules3.rs index f2bb05038..8f8c4fe89 100644 --- a/exercises/modules/modules3.rs +++ b/exercises/modules/modules3.rs @@ -8,10 +8,10 @@ // Execute `rustlings hint modules3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE // TODO: Complete this use statement -use ??? +use std::time::SystemTime; +use std::time::UNIX_EPOCH; fn main() { match SystemTime::now().duration_since(UNIX_EPOCH) { diff --git a/exercises/options/options1.rs b/exercises/options/options1.rs index e131b48b9..97d569a1b 100644 --- a/exercises/options/options1.rs +++ b/exercises/options/options1.rs @@ -3,7 +3,6 @@ // Execute `rustlings hint options1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE // 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 @@ -13,7 +12,7 @@ fn maybe_icecream(time_of_day: u16) -> Option { // 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>23{None} else if time_of_day >21 {Some(0)} else {Some(5)} } #[cfg(test)] @@ -34,6 +33,6 @@ mod tests { // TODO: Fix this test. How do you get at the value contained in the // Option? let icecreams = maybe_icecream(12); - assert_eq!(icecreams, 5); + assert_eq!(icecreams, Some(5)); } } diff --git a/exercises/options/options2.rs b/exercises/options/options2.rs index 4d998e7d0..80c5f45fe 100644 --- a/exercises/options/options2.rs +++ b/exercises/options/options2.rs @@ -3,7 +3,6 @@ // Execute `rustlings hint options2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE #[cfg(test)] mod tests { @@ -13,7 +12,7 @@ mod tests { let optional_target = Some(target); // TODO: Make this an if let statement whose value is "Some" type - word = optional_target { + if let Some(word) = optional_target { assert_eq!(word, target); } } @@ -32,7 +31,7 @@ mod tests { // TODO: make this a while let statement - remember that vector.pop also // adds another layer of Option. You can stack `Option`s into // while let and if let. - integer = optional_integers.pop() { + while let Some(Some(integer)) = optional_integers.pop() { assert_eq!(integer, cursor); cursor -= 1; } diff --git a/exercises/options/options3.rs b/exercises/options/options3.rs index 23c15eab8..a653dd35c 100644 --- a/exercises/options/options3.rs +++ b/exercises/options/options3.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint options3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + struct Point { x: i32, @@ -14,7 +14,7 @@ fn main() { let y: Option = Some(Point { x: 100, y: 200 }); match y { - Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y), + Some(ref p) => println!("Co-ordinates are {},{} ", p.x, p.y), _ => panic!("no match!"), } y; // Fix without deleting this line. diff --git a/exercises/quiz2.rs b/exercises/quiz2.rs index 29925cafc..0bdc4937e 100644 --- a/exercises/quiz2.rs +++ b/exercises/quiz2.rs @@ -20,7 +20,7 @@ // // No hints this time! -// I AM NOT DONE + pub enum Command { Uppercase, @@ -32,11 +32,26 @@ mod my_module { use super::Command; // TODO: Complete the function signature! - pub fn transformer(input: ???) -> ??? { + pub fn transformer(input: Vec<(String,Command)>) -> Vec { // TODO: Complete the output declaration! - let mut output: ??? = vec![]; + let mut output: Vec = vec![]; for (string, command) in input.iter() { // TODO: Complete the function body. You can do it! + match command{ + Command::Uppercase => { + output.push(string.to_uppercase()); + }, + Command::Trim => { + output.push(string.trim().to_string()); + }, + Command::Append(x) =>{ + let mut str = string.to_string(); + for i in 1..=(*x as u32) { + str.push_str("bar"); + } + output.push(str); + } + } } output } @@ -45,7 +60,7 @@ mod my_module { #[cfg(test)] mod tests { // TODO: What do we need to import to have `transformer` in scope? - use ???; + use crate::my_module::transformer; use super::Command; #[test] diff --git a/exercises/quiz3.rs b/exercises/quiz3.rs index 3b01d3132..d36fab7eb 100644 --- a/exercises/quiz3.rs +++ b/exercises/quiz3.rs @@ -16,15 +16,15 @@ // // Execute `rustlings hint quiz3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE -pub struct ReportCard { - pub grade: f32, + +pub struct ReportCard { + pub grade: T, pub student_name: String, pub student_age: u8, } -impl ReportCard { +impl ReportCard { pub fn print(&self) -> String { format!("{} ({}) - achieved a grade of {}", &self.student_name, &self.student_age, &self.grade) @@ -52,7 +52,7 @@ mod tests { 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, }; diff --git a/exercises/smart_pointers/arc1.rs b/exercises/smart_pointers/arc1.rs index 3526ddcb9..74a77b465 100644 --- a/exercises/smart_pointers/arc1.rs +++ b/exercises/smart_pointers/arc1.rs @@ -21,7 +21,6 @@ // // Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE #![forbid(unused_imports)] // Do not change this, (or the next) line. use std::sync::Arc; @@ -29,11 +28,11 @@ use std::thread; fn main() { let numbers: Vec<_> = (0..100u32).collect(); - let shared_numbers = // TODO + let shared_numbers = Arc::new(numbers); // TODO let mut joinhandles = Vec::new(); for offset in 0..8 { - let child_numbers = // TODO + 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); diff --git a/exercises/smart_pointers/box1.rs b/exercises/smart_pointers/box1.rs index 513e7daa3..3af38790e 100644 --- a/exercises/smart_pointers/box1.rs +++ b/exercises/smart_pointers/box1.rs @@ -18,11 +18,10 @@ // // Execute `rustlings hint box1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE #[derive(PartialEq, Debug)] pub enum List { - Cons(i32, List), + Cons(i32,Box), Nil, } @@ -35,11 +34,11 @@ fn main() { } pub fn create_empty_list() -> List { - todo!() + List::Nil } pub fn create_non_empty_list() -> List { - todo!() + List::Cons(0,Box::new(List::Nil)) } #[cfg(test)] diff --git a/exercises/smart_pointers/cow1.rs b/exercises/smart_pointers/cow1.rs index 7ca916866..02d0d74cc 100644 --- a/exercises/smart_pointers/cow1.rs +++ b/exercises/smart_pointers/cow1.rs @@ -12,7 +12,6 @@ // // Execute `rustlings hint cow1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE use std::borrow::Cow; @@ -48,7 +47,8 @@ mod tests { let slice = [0, 1, 2]; let mut input = Cow::from(&slice[..]); match abs_all(&mut input) { - // TODO + Cow::Borrowed (_) => Ok(()), + _ => Err("Expected owned value"), } } @@ -60,7 +60,8 @@ mod tests { 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"), } } @@ -72,7 +73,8 @@ mod tests { 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"), } } } diff --git a/exercises/smart_pointers/rc1.rs b/exercises/smart_pointers/rc1.rs index ad3f1ce29..1227b4594 100644 --- a/exercises/smart_pointers/rc1.rs +++ b/exercises/smart_pointers/rc1.rs @@ -10,7 +10,7 @@ // // Execute `rustlings hint rc1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE + use std::rc::Rc; @@ -60,17 +60,17 @@ fn main() { jupiter.details(); // TODO - let saturn = Planet::Saturn(Rc::new(Sun {})); + let saturn = Planet::Saturn(Rc::clone(&sun)); println!("reference count = {}", Rc::strong_count(&sun)); // 7 references saturn.details(); // TODO - let uranus = Planet::Uranus(Rc::new(Sun {})); + let uranus = Planet::Uranus(Rc::clone(&sun)); println!("reference count = {}", Rc::strong_count(&sun)); // 8 references uranus.details(); // TODO - let neptune = Planet::Neptune(Rc::new(Sun {})); + let neptune = Planet::Neptune(Rc::clone(&sun)); println!("reference count = {}", Rc::strong_count(&sun)); // 9 references neptune.details(); @@ -92,12 +92,15 @@ fn main() { 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); diff --git a/exercises/strings/strings1.rs b/exercises/strings/strings1.rs index f50e1fa98..5d48b91b5 100644 --- a/exercises/strings/strings1.rs +++ b/exercises/strings/strings1.rs @@ -5,7 +5,6 @@ // Execute `rustlings hint strings1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE fn main() { let answer = current_favorite_color(); @@ -13,5 +12,5 @@ fn main() { } fn current_favorite_color() -> String { - "blue" + "blue".to_string() } diff --git a/exercises/strings/strings2.rs b/exercises/strings/strings2.rs index 4d95d16a1..eeb560c52 100644 --- a/exercises/strings/strings2.rs +++ b/exercises/strings/strings2.rs @@ -5,10 +5,9 @@ // Execute `rustlings hint strings2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE fn main() { - let word = String::from("green"); // Try not changing this line :) + let word = "green"; // Try not changing this line :) if is_a_color_word(word) { println!("That is a color word I know!"); } else { diff --git a/exercises/strings/strings3.rs b/exercises/strings/strings3.rs index b29f9325b..b01bc61fb 100644 --- a/exercises/strings/strings3.rs +++ b/exercises/strings/strings3.rs @@ -3,21 +3,20 @@ // Execute `rustlings hint strings3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE 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.trim().to_string() +" world!" } fn replace_me(input: &str) -> String { // TODO: Replace "cars" in the string with "balloons"! - ??? + input.to_string().replace("cars","balloons") } #[cfg(test)] diff --git a/exercises/strings/strings4.rs b/exercises/strings/strings4.rs index e8c54acc5..d603c3c28 100644 --- a/exercises/strings/strings4.rs +++ b/exercises/strings/strings4.rs @@ -7,7 +7,6 @@ // // No hints this time! -// I AM NOT DONE fn string_slice(arg: &str) { println!("{}", arg); @@ -17,14 +16,14 @@ fn string(arg: String) { } fn main() { - ???("blue"); - ???("red".to_string()); - ???(String::from("hi")); - ???("rust is fun!".to_owned()); - ???("nice weather".into()); - ???(format!("Interpolation {}", "Station")); - ???(&String::from("abc")[0..1]); - ???(" hello there ".trim()); - ???("Happy Monday!".to_string().replace("Mon", "Tues")); - ???("mY sHiFt KeY iS sTiCkY".to_lowercase()); + string_slice("blue"); + string("red".to_string()); + string(String::from("hi")); + string("rust is fun!".to_owned()); + string_slice("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()); } diff --git a/exercises/structs/structs1.rs b/exercises/structs/structs1.rs index 5fa5821c5..b6d6d4500 100644 --- a/exercises/structs/structs1.rs +++ b/exercises/structs/structs1.rs @@ -5,13 +5,15 @@ // Execute `rustlings hint structs1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE struct ColorClassicStruct { // TODO: Something goes here + red:i32, + green:i32, + blue:i32 } -struct ColorTupleStruct(/* TODO: Something goes here */); +struct ColorTupleStruct(i32,i32,i32); #[derive(Debug)] struct UnitLikeStruct; @@ -24,7 +26,7 @@ mod tests { fn classic_c_structs() { // TODO: Instantiate a classic c struct! // let green = - + let green = ColorClassicStruct{red: 0,green: 255,blue: 0};; assert_eq!(green.red, 0); assert_eq!(green.green, 255); assert_eq!(green.blue, 0); @@ -34,7 +36,7 @@ mod tests { fn tuple_structs() { // TODO: Instantiate a tuple struct! // let green = - + let green = ColorTupleStruct(0,255,0); assert_eq!(green.0, 0); assert_eq!(green.1, 255); assert_eq!(green.2, 0); @@ -44,6 +46,7 @@ mod tests { fn unit_structs() { // TODO: Instantiate a unit-like struct! // let unit_like_struct = + let unit_like_struct =UnitLikeStruct; let message = format!("{:?}s are fun!", unit_like_struct); assert_eq!(message, "UnitLikeStructs are fun!"); diff --git a/exercises/structs/structs2.rs b/exercises/structs/structs2.rs index 328567f03..339d3ce08 100644 --- a/exercises/structs/structs2.rs +++ b/exercises/structs/structs2.rs @@ -5,8 +5,6 @@ // Execute `rustlings hint structs2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - #[derive(Debug)] struct Order { name: String, @@ -38,7 +36,9 @@ mod tests { fn your_order() { let order_template = create_order_template(); // TODO: Create your own order using the update syntax and template above! - // let your_order = + let mut your_order = create_order_template(); + your_order.name = "Hacker in Rust".to_string(); + your_order.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); diff --git a/exercises/structs/structs3.rs b/exercises/structs/structs3.rs index 4851317c5..6a2efec06 100644 --- a/exercises/structs/structs3.rs +++ b/exercises/structs/structs3.rs @@ -7,8 +7,6 @@ // Execute `rustlings hint structs3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - #[derive(Debug)] struct Package { sender_country: String, @@ -29,12 +27,14 @@ impl Package { } } - fn is_international(&self) -> ??? { + fn is_international(&self) -> bool { // Something goes here... + self.recipient_country!=self.sender_country } - fn get_fees(&self, cents_per_gram: i32) -> ??? { + fn get_fees(&self, cents_per_gram: i32) -> i32 { // Something goes here... + self.weight_in_grams*cents_per_gram } } diff --git a/exercises/tests/Cargo.lock b/exercises/tests/Cargo.lock new file mode 100644 index 000000000..d3a8d8c09 --- /dev/null +++ b/exercises/tests/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "tests8" +version = "0.0.1" diff --git a/exercises/tests/Cargo.toml b/exercises/tests/Cargo.toml new file mode 100644 index 000000000..646d1f04e --- /dev/null +++ b/exercises/tests/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "tests8" +version = "0.0.1" +edition = "2021" +[[bin]] +name = "tests8" +path = "tests8.rs" \ No newline at end of file diff --git a/exercises/tests/build.rs b/exercises/tests/build.rs index aa518cef2..b5e869f43 100644 --- a/exercises/tests/build.rs +++ b/exercises/tests/build.rs @@ -10,15 +10,16 @@ fn main() { .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs(); // What's the use of this timestamp here? + let your_command = format!( - "Your command here with {}, please checkout exercises/tests/build.rs", - timestamp + "rustc-env=TEST_FOO={}", + timestamp, ); println!("cargo:{}", your_command); // In tests8, we should enable "pass" feature to make the // testcase return early. Fill in the command to tell // Cargo about that. - let your_command = "Your command here, please checkout exercises/tests/build.rs"; + let your_command = "rustc-cfg=feature=\"pass\""; println!("cargo:{}", your_command); } diff --git a/exercises/tests/tests1.rs b/exercises/tests/tests1.rs index 810277ac3..1f07b4083 100644 --- a/exercises/tests/tests1.rs +++ b/exercises/tests/tests1.rs @@ -10,12 +10,12 @@ // Execute `rustlings hint tests1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + #[cfg(test)] mod tests { #[test] fn you_can_assert() { - assert!(); + assert!(true); } } diff --git a/exercises/tests/tests2.rs b/exercises/tests/tests2.rs index f8024e9f2..402d55ba4 100644 --- a/exercises/tests/tests2.rs +++ b/exercises/tests/tests2.rs @@ -6,12 +6,12 @@ // Execute `rustlings hint tests2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + #[cfg(test)] mod tests { #[test] fn you_can_assert_eq() { - assert_eq!(); + assert_eq!(1,1); } } diff --git a/exercises/tests/tests3.rs b/exercises/tests/tests3.rs index 4013e3841..1b678c4fd 100644 --- a/exercises/tests/tests3.rs +++ b/exercises/tests/tests3.rs @@ -7,7 +7,7 @@ // Execute `rustlings hint tests3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + pub fn is_even(num: i32) -> bool { num % 2 == 0 @@ -19,11 +19,11 @@ mod tests { #[test] fn is_true_when_even() { - assert!(); + assert!(is_even(2)); } #[test] fn is_false_when_odd() { - assert!(); + assert!(!is_even(3)); } } diff --git a/exercises/tests/tests4.rs b/exercises/tests/tests4.rs index 935d0db17..ea88b746c 100644 --- a/exercises/tests/tests4.rs +++ b/exercises/tests/tests4.rs @@ -5,7 +5,7 @@ // Execute `rustlings hint tests4` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + struct Rectangle { width: i32, @@ -30,17 +30,19 @@ mod tests { 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!(???, 10); // check width - assert_eq!(???, 20); // check height + 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); diff --git a/exercises/tests/tests5.rs b/exercises/tests/tests5.rs index 0cd5cb256..b11849446 100644 --- a/exercises/tests/tests5.rs +++ b/exercises/tests/tests5.rs @@ -22,7 +22,7 @@ // Execute `rustlings hint tests5` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + /// # Safety /// @@ -32,7 +32,8 @@ unsafe fn modify_by_address(address: usize) { // code's behavior and the contract of this function. You may use the // comment of the test below as your format reference. unsafe { - todo!("Your code goes here") + //todo!("Your code goes here") + address as u32; } } @@ -46,6 +47,7 @@ mod tests { // 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); + println!("{t}"); + assert!(t == 0x12345678); } } diff --git a/exercises/tests/tests6.rs b/exercises/tests/tests6.rs index 4c913779d..adc084c12 100644 --- a/exercises/tests/tests6.rs +++ b/exercises/tests/tests6.rs @@ -7,7 +7,7 @@ // Execute `rustlings hint tests6` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + struct Foo { a: u128, @@ -20,8 +20,10 @@ struct Foo { unsafe fn raw_pointer_to_box(ptr: *mut Foo) -> Box { // SAFETY: The `ptr` contains an owned box of `Foo` by contract. We // simply reconstruct the box from that pointer. - let mut ret: Box = unsafe { ??? }; - todo!("The rest of the code goes here") + let mut ret: Box = unsafe { Box::from_raw(ptr) }; + ret.b = Some("hello".to_owned()); + ret + //todo!("The rest of the code goes here") } #[cfg(test)] diff --git a/exercises/tests/tests7.rs b/exercises/tests/tests7.rs index 66b37b72d..09574783e 100644 --- a/exercises/tests/tests7.rs +++ b/exercises/tests/tests7.rs @@ -34,7 +34,6 @@ // Execute `rustlings hint tests7` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE fn main() {} diff --git a/exercises/tests/tests8.rs b/exercises/tests/tests8.rs index ce7e35d8d..b9eb0fb10 100644 --- a/exercises/tests/tests8.rs +++ b/exercises/tests/tests8.rs @@ -7,7 +7,6 @@ // Execute `rustlings hint tests8` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE fn main() {} diff --git a/exercises/tests/tests9.rs b/exercises/tests/tests9.rs index ea2a8ec02..d7229ce24 100644 --- a/exercises/tests/tests9.rs +++ b/exercises/tests/tests9.rs @@ -3,39 +3,41 @@ // Rust is highly capable of sharing FFI interfaces with C/C++ and other statically compiled // languages, and it can even link within the code itself! It makes it through the extern // block, just like the code below. -// + // The short string after the `extern` keyword indicates which ABI the externally imported // function would follow. In this exercise, "Rust" is used, while other variants exists like // "C" for standard C ABI, "stdcall" for the Windows ABI. -// + // The externally imported functions are declared in the extern blocks, with a semicolon to // mark the end of signature instead of curly braces. Some attributes can be applied to those // function declarations to modify the linking behavior, such as #[link_name = ".."] to // modify the actual symbol names. -// + // If you want to export your symbol to the linking environment, the `extern` keyword can // also be marked before a function definition with the same ABI string note. The default ABI // for Rust functions is literally "Rust", so if you want to link against pure Rust functions, // the whole extern term can be omitted. -// + // Rust mangles symbols by default, just like C++ does. To suppress this behavior and make // those functions addressable by name, the attribute #[no_mangle] can be applied. -// + // In this exercise, your task is to make the testcase able to call the `my_demo_function` in // module Foo. the `my_demo_function_alias` is an alias for `my_demo_function`, so the two // line of code in the testcase should call the same function. -// + // You should NOT modify any existing code except for adding two lines of attributes. -// I AM NOT DONE + extern "Rust" { fn my_demo_function(a: u32) -> u32; + #[link_name = "my_demo_function"] fn my_demo_function_alias(a: u32) -> u32; } mod Foo { // No `extern` equals `extern "Rust"`. + #[no_mangle] fn my_demo_function(a: u32) -> u32 { a } diff --git a/exercises/threads/threads1.rs b/exercises/threads/threads1.rs index 80b6def3e..37c8968dc 100644 --- a/exercises/threads/threads1.rs +++ b/exercises/threads/threads1.rs @@ -8,7 +8,7 @@ // Execute `rustlings hint threads1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + use std::thread; use std::time::{Duration, Instant}; @@ -27,6 +27,8 @@ fn main() { let mut results: Vec = vec![]; for handle in handles { // TODO: a struct is returned from thread::spawn, can you use it? + let result = handle.join().unwrap(); + results.push(result); } if results.len() != 10 { diff --git a/exercises/threads/threads2.rs b/exercises/threads/threads2.rs index 62dad80d6..64f9be55e 100644 --- a/exercises/threads/threads2.rs +++ b/exercises/threads/threads2.rs @@ -7,25 +7,26 @@ // Execute `rustlings hint threads2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + use std::sync::Arc; use std::thread; use std::time::Duration; - +use std::sync::Mutex; struct JobStatus { jobs_completed: u32, } fn main() { - let status = Arc::new(JobStatus { jobs_completed: 0 }); + 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)); + let mut munber = status_shared.lock().unwrap(); // TODO: You must take an action before you update a shared value - status_shared.jobs_completed += 1; + munber.jobs_completed += 1; }); handles.push(handle); } @@ -34,6 +35,7 @@ fn main() { // 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 {}", ???); + //println!("jobs completed {}", status.jobs_completed); } + println!("jobs completed {}", status.lock().unwrap().jobs_completed); } diff --git a/exercises/threads/threads3.rs b/exercises/threads/threads3.rs index db7d41ba6..cb27ada48 100644 --- a/exercises/threads/threads3.rs +++ b/exercises/threads/threads3.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint threads3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + use std::sync::mpsc; use std::sync::Arc; @@ -31,10 +31,11 @@ fn send_tx(q: Queue, tx: mpsc::Sender) -> () { let qc1 = Arc::clone(&qc); let qc2 = Arc::clone(&qc); + let tx1 = tx.clone(); thread::spawn(move || { for val in &qc1.first_half { println!("sending {:?}", val); - tx.send(*val).unwrap(); + tx1.send(*val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); diff --git a/exercises/traits/traits1.rs b/exercises/traits/traits1.rs index 37dfcbfe8..9998232d8 100644 --- a/exercises/traits/traits1.rs +++ b/exercises/traits/traits1.rs @@ -7,7 +7,7 @@ // Execute `rustlings hint traits1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + trait AppendBar { fn append_bar(self) -> Self; @@ -15,6 +15,9 @@ trait AppendBar { impl AppendBar for String { // TODO: Implement `AppendBar` for type `String`. + fn append_bar(self) -> Self{ + self+"Bar" + } } fn main() { diff --git a/exercises/traits/traits2.rs b/exercises/traits/traits2.rs index 3e35f8e11..7c0c92b08 100644 --- a/exercises/traits/traits2.rs +++ b/exercises/traits/traits2.rs @@ -8,7 +8,7 @@ // // Execute `rustlings hint traits2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE + trait AppendBar { fn append_bar(self) -> Self; @@ -16,6 +16,13 @@ trait AppendBar { // TODO: Implement trait `AppendBar` for a vector of strings. +impl AppendBar for Vec { + fn append_bar(mut self) -> Self{ + self.push(String::from("Bar")); + self + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/exercises/traits/traits3.rs b/exercises/traits/traits3.rs index 4e2b06b0e..621ebdb45 100644 --- a/exercises/traits/traits3.rs +++ b/exercises/traits/traits3.rs @@ -8,10 +8,11 @@ // Execute `rustlings hint traits3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE pub trait Licensed { - fn licensing_info(&self) -> String; + fn licensing_info(&self) -> String{ + String::from("Some information") + } } struct SomeSoftware { diff --git a/exercises/traits/traits4.rs b/exercises/traits/traits4.rs index 4bda3e571..b998b5f0e 100644 --- a/exercises/traits/traits4.rs +++ b/exercises/traits/traits4.rs @@ -7,7 +7,6 @@ // Execute `rustlings hint traits4` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE pub trait Licensed { fn licensing_info(&self) -> String { @@ -23,7 +22,7 @@ impl Licensed for SomeSoftware {} impl Licensed for OtherSoftware {} // YOU MAY ONLY CHANGE THE NEXT LINE -fn compare_license_types(software: ??, software_two: ??) -> bool { +fn compare_license_types(software:impl Licensed, software_two:impl Licensed) -> bool { software.licensing_info() == software_two.licensing_info() } diff --git a/exercises/traits/traits5.rs b/exercises/traits/traits5.rs index df1838054..58cc8f79a 100644 --- a/exercises/traits/traits5.rs +++ b/exercises/traits/traits5.rs @@ -7,7 +7,7 @@ // Execute `rustlings hint traits5` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + pub trait SomeTrait { fn some_function(&self) -> bool { @@ -30,7 +30,7 @@ impl SomeTrait for OtherStruct {} impl OtherTrait for OtherStruct {} // YOU MAY ONLY CHANGE THE NEXT LINE -fn some_func(item: ??) -> bool { +fn some_func(item: T) -> bool { item.some_function() && item.other_function() } diff --git a/temp_225122_ThreadId1 b/temp_225122_ThreadId1 new file mode 100755 index 000000000..993289e9b Binary files /dev/null and b/temp_225122_ThreadId1 differ