With this playground code I can get the square of x, but x value is not changed unless I reassign it again.
i.e. is there a away to get:
let x = 5;
x.squared(); // how to change the trait of this
println!("{}", x); // to make this print 25 not 5
The same code in the play ground is below:
trait SquareExt {
fn square(self) -> Self;
}
impl SquareExt for i32 {
fn square(self) -> Self { self * self }
}
fn main() {
let mut x = 5;
x = x.square(); // I want to avoid this, and make it as x.square() only
println!("{}", x);
}
Of course, you must define x as mutable, otherwise the unique reference would be impossible to create. If you need to work through shared reference for some reason, you should look for some Cell.
Thanks a lot, for my need as I do not want to assign the value for other element I changed the signature from fn square(&mut self) -> Self; to fn square(&mut self);