Changing element value through extension

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);
}

To change the receiver value, you must take it by unique reference. Check this:

trait SquareExt {
    fn square(&mut self) -> Self;
}

impl SquareExt for i32 {
    fn square(&mut self) -> Self {
        *self = *self * *self;
        *self
    }
}

fn main() {
    let mut x = 5;
    x.square();
    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.

I came up with the same thing as @Cerber-Ursi basically. I wrapped the i32 in a type but otherwise same idea. playground

1 Like

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);

trait SquareExt {
    fn square(&mut self);
}

impl SquareExt for i32 {
    fn square(&mut self) -> () {
        *self = *self * *self;
    }
}

fn main() {
    let mut x = 4;
    x.square();
    println!("{}", x);
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.