mirror of
https://github.com/rust-lang/rustlings.git
synced 2026-01-10 12:49:18 +00:00
conversion: Mut generic, also for Box, TO CHECK! as_ref_mut
This commit is contained in:
parent
237ac327b4
commit
aba953ba85
@ -9,23 +9,31 @@
|
||||
|
||||
// I AM NOT DONE
|
||||
|
||||
use std::fmt::Debug;
|
||||
|
||||
// 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>(arg: T) -> usize {
|
||||
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>(arg: T) -> usize {
|
||||
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 : std::ops::Add<Output = T>>(arg: &mut T) {
|
||||
// First version that works for mut ref of a num, but it doesn't work if the num is inside something like Box
|
||||
// fn num_sq<T : std::ops::Add<Output = T> + AsMut<i32>>(arg: &mut T) {
|
||||
fn num_sq<T, U>(arg: &mut T)
|
||||
where
|
||||
T : AsMut<U> + std::fmt::Debug, // generalised version where T is a generic container and U is the numeric type
|
||||
U : std::ops::Mul<Output = U> + Copy
|
||||
{
|
||||
// TODO: Implement the function body.
|
||||
arg = arg * arg;
|
||||
*arg.as_mut() = *arg.as_mut() * *arg.as_mut();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user