Can rust macros generate getters that are Copy aware?

Viewed 158

derive-getters is a nice crate that will create getters for you. However, it always generates getters that return a reference, even for Copy types. For example for this struct:

#[derive(Getters)]
pub struct MyCheesyStruct {
    x: i64,
    y: i64,
}

It will generate:

impl MyCheesyStruct {
    pub fn x(&self) -> &i64 {
        &self.x
    }

    pub fn y(&self) -> &i64 {
        &self.y
    }
}

This makes things more cumbersome for users than they need to be, because i64 implements Copy. So I started to wonder if it was possible to do better? But macros operate at the token level, so they don't know anything about types/traits. Is there a way to get this functionality, short of manually annotating members with a directive to specify they should be returned without a borrow? This is the kind of thing type level metaprogramming in C++ excels at.

1 Answers

So I started to wonder if it was possible to do better?

As partial answer I can say that it is doable for primitive types out of the box. For other types you might require additional annotation on the field something like that:

#[derive(Copy)]
pub struct Point {
  x: i64,
  y: i64,
}

#[derive(Getters)]
pub struct MyCheesyStruct {
    #[noref] // generates non-borrow getter
    point: Point,
}

Or you can make a version of procedural macro that generates non-borrow getters for all fields.

Related