use std::fmt::Error;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)) }}
let v1: Vec<i32> = vec![1, 2, 3];let v2: Vec<_> = v1.iter().map(|x| x + 1).collect();assert_eq!(v2, vec![2, 3, 4]);
collect会自动根据指定类型对数据进行收集
// 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]; 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() -> Vec<Result<i32, DivisionError>> { let numbers = vec![27, 297, 38502, 81]; let division_results = numbers.into_iter().map(|n| divide(n, 27)).collect(); division_results}
product直接将迭代器元素相乘,返回一个迭代器
pub fn factorial(num: u64) -> u64 { // Complete this function to return the factorial of num // Do not use: // - return // Try not to use: // - imperative style loops (for, while) // - additional variables // For an extra challenge, don't use: // - recursion // Execute `rustlings hint iterators4` for hints. (1..num + 1).product()}// 实现阶乘
具体来说,如果我们有一个类型 T,并且希望将其转换为类型 U 的引用,我们可以实现 AsRef <U> trait 来完成这个转换。在实现中,我们需要提供一个名为 as_ref 的方法,该方法返回类型 &U。这样,我们就可以使用 as_ref 方法来将 T 转换为 U 的引用。
// Obtain the number of bytes (not characters) in the given argument.// TODO: Add the AsRef trait appropriately as a trait bound.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()}
AsMut <T> 是一个标准库中定义的 trait,它将类型 T 转换为一个指向其内部值的可变引用。当我们在泛型函数中使用 T: AsMut <u32> 这个 trait bound 时,我们告诉编译器要求 T 类型必须具备将其内部值作为 u32 类型的可变引用的能力
// 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()}