rustlings

solving rustlings ft. dracuxan
git clone [email protected]:dracuxan/rustlings.git
Log | Files | Refs

as_ref_mut.rs (1677B)


      1 // AsRef and AsMut allow for cheap reference-to-reference conversions. Read more
      2 // about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html and
      3 // https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively.
      4 
      5 // Obtain the number of bytes (not characters) in the given argument
      6 // (`.len()` returns the number of bytes in a string).
      7 // TODO: Add the `AsRef` trait appropriately as a trait bound.
      8 fn byte_counter<T>(arg: T) -> usize {
      9     arg.as_ref().len()
     10 }
     11 
     12 // Obtain the number of characters (not bytes) in the given argument.
     13 // TODO: Add the `AsRef` trait appropriately as a trait bound.
     14 fn char_counter<T>(arg: T) -> usize {
     15     arg.as_ref().chars().count()
     16 }
     17 
     18 // Squares a number using `as_mut()`.
     19 // TODO: Add the appropriate trait bound.
     20 fn num_sq<T>(arg: &mut T) {
     21     // TODO: Implement the function body.
     22 }
     23 
     24 fn main() {
     25     // You can optionally experiment here.
     26 }
     27 
     28 #[cfg(test)]
     29 mod tests {
     30     use super::*;
     31 
     32     #[test]
     33     fn different_counts() {
     34         let s = "Café au lait";
     35         assert_ne!(char_counter(s), byte_counter(s));
     36     }
     37 
     38     #[test]
     39     fn same_counts() {
     40         let s = "Cafe au lait";
     41         assert_eq!(char_counter(s), byte_counter(s));
     42     }
     43 
     44     #[test]
     45     fn different_counts_using_string() {
     46         let s = String::from("Café au lait");
     47         assert_ne!(char_counter(s.clone()), byte_counter(s));
     48     }
     49 
     50     #[test]
     51     fn same_counts_using_string() {
     52         let s = String::from("Cafe au lait");
     53         assert_eq!(char_counter(s.clone()), byte_counter(s));
     54     }
     55 
     56     #[test]
     57     fn mut_box() {
     58         let mut num: Box<u32> = Box::new(3);
     59         num_sq(&mut num);
     60         assert_eq!(*num, 9);
     61     }
     62 }