Rust shorthand for writing one line functions

Besides macros, does Rust has a shorthand for writing one line functions? I have a bunch of files of the form:

impl SomeTrait for ... {
    #[inline(always)]
    fn s_iii(lhs: i32, rhs: i32) -> i32 {
        lhs + rhs
    }

    #[inline(always)]
    fn s_iff(lhs: i32, rhs: f32) -> f32 {
        (lhs as f32) + rhs
    }

    #[inline(always)]
    fn s_fif(lhs: f32, rhs: i32) -> f32 {
        lhs + (rhs as f32)
    }

    #[inline(always)]
    fn s_fff(lhs: f32, rhs: f32) -> f32 {
        lhs + rhs
    }
}

I am wondering if there is a way to collapse each 3 line fn to a 1 line fn.

Maybe I'm missing something obvious but what's wrong with:

#[inline(always)] fn s_fff(lhs: f32, rhs: f32) -> f32 { lhs + rhs }

Why not this?

impl SomeTrait for ... {
    #[inline(always)]
    fn s_iii(lhs: i32, rhs: i32) -> i32 { lhs + rhs }
    #[inline(always)]
    fn s_iff(lhs: i32, rhs: f32) -> f32 { (lhs as f32) + rhs }
    #[inline(always)]
    fn s_fif(lhs: f32, rhs: i32) -> f32 { lhs + (rhs as f32) }
    #[inline(always)]
    fn s_fff(lhs: f32, rhs: f32) -> f32 { lhs + rhs }
}

@chrisd , @TheNappap
Sorry for not being clear: I'm using rust-fmt, which would expand both of those into three lines.

In particular, I'm in IntelliJ/VIM hitting Shift-J (join lines), and then upon saving, rust-fmt expands it out

You can use #[rustfmt::skip] for just that block.

#[rustfmt::skip] // Allow single line functions.
impl SomeTrait for ... {
    #[inline(always)]
    fn s_iii(lhs: i32, rhs: i32) -> i32 { lhs + rhs }
    #[inline(always)]
    fn s_iff(lhs: i32, rhs: f32) -> f32 { (lhs as f32) + rhs }
    #[inline(always)]
    fn s_fif(lhs: f32, rhs: i32) -> f32 { lhs + (rhs as f32) }
    #[inline(always)]
    fn s_fff(lhs: f32, rhs: f32) -> f32 { lhs + rhs }
}
2 Likes

Personally I agree with rust_fmt. Things are much clearer when the different components are on separate lines.

Lines are cheap now a days. Why not breath a little?

1 Like

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