Concatenate methods

Hi,

Actually I do not know how is this called but i know how a solution should looks like. Let say I have the following example:


let x = Some("xx");

let a = x.unwrap().to_string();

So here I applied two manipulations on x . First I unwrapped it and then converted it. If I were to create my own two methods that operate on x let say the first one (given x is an int) adds 50 to it and the second multiplies it by 10. and let say I wanna have the same interface as the one above, how would I go about it.

let x= 2;
x.add(50).mul(10); // and now my x = 520 

any pointers ? Where to start ? how to create such methods ?

Traits are the way to add new methods to a type. First use the trait keyword to define the interface to your trait:

trait DoStuff {
    fn add(self, other: Self) -> Self;
    fn mul(self, other: Self) -> Self;
}

Then implement your trait for one or more types using the impl keyword:

impl DoStuff for i32 {
    fn add(self, other: i32) -> i32 { self + other }
    fn mul(self, other: i32) -> i32 { self * other }
}

and then you can call that trait's methods in any module where the trait's name is in scope:

println!("{}", 2i32.add(50).mul(10));

Complete example on the playground

Side note: In this particular case, the std::ops module already defines traits with add and mul methods, so you can just import these existing traits instead of defining new ones (playground):

use std::ops::{Add, Mul};
println!("{}", 2i32.add(50).mul(10));
2 Likes

The word is function composition.

1 Like

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