I'm following the 'rust by example' documentation since it is some time that I don't program in Rust, and I'm having some problem on the 2nd activity proposed in this page. Basically, It's asking me to swap the digits of a floating-point number, the firsts before and after the floating point. I created this function:
fn reverse_floating_point(f:f32) -> f32{
let is_positive = f.is_sign_positive();
let clone = format!("{:.1}",f);
let mut clone = clone.chars();
// if number is negative, don't take the '-'
let first: char = match is_positive {
true => clone.next().unwrap(),
false => {
clone.next();
clone.next().unwrap()
},
};
let last = clone.last().unwrap();
// if number is negative, add the '-'
match is_positive {
true => format!("{last}.{first}").parse::<f32>().unwrap(),
false => format!("-{last}.{first}").parse::<f32>().unwrap(),
}
}
which it seems to work but it is not the intended way that the book suggests since it should be an exercise for tuples, probably with a function that takes an f32 and returns a (i32,i32), which can be easily swapped. How can I do it?
EDIT:
I'm starting with an f32 and not with a (i32,i32) because the function is supposed to be an implementation for the Matrix tuple struct that has for fields (f32,f32,f32,f32). For reference, this is what I wrote:
use std::fmt;
#[derive(Debug)]
pub struct Matrix(
pub f32,
pub f32,
pub f32,
pub f32
);
impl Matrix {
pub fn transpose(&self) -> Matrix {
Matrix(
Self::reverse_floating_point(self.0),
Self::reverse_floating_point(self.1),
Self::reverse_floating_point(self.2),
Self::reverse_floating_point(self.3),
)
}
fn reverse_floating_point(f:f32) -> f32{
let is_positive = f.is_sign_positive();
let clone = format!("{:.1}",f);
let mut clone = clone.chars();
// if number is negative, don't take the '-'
let first = match is_positive {
true => clone.next().unwrap(),
false => {
clone.next();
clone.next().unwrap()
},
};
let last = clone.last().unwrap();
// if number is negative, add the '-'
match is_positive {
true => format!("{last}.{first}").parse::<f32>().unwrap(),
false => format!("-{last}.{first}").parse::<f32>().unwrap(),
}
}
}
impl fmt::Display for Matrix {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f,"( {:.1}, {:.1} )\n( {:.1}, {:.1} )",self.0,self.1,self.2,self.3)
}
}