rbrich
rbrich

Reputation: 135

What trait tells the compiler that `T` is simple type with implicit copy?

I intend to use the following struct with simple numeric types like i32, usize, but in the implementation of the contains() method, Rust forces me to use Clone instead of an implicit copy ("cannot move out of borrowed content").

I did not find any trait that would tell the compiler that T is simple type with implicit copy. Can I count on the compiler that the clone() call will be discarded for numeric types, without any performance hit?

pub struct Rect<T> {
    pub x: T,
    pub y: T,
    pub w: T,
    pub h: T,
}

impl<T> Rect<T> where T: PartialOrd + Add<T, Output=T> + Clone {
    pub fn contains(&self, x: T, y: T) -> bool {
        x >= self.x && y >= self.y
            && x < self.x.clone() + self.w.clone()
            && y < self.y.clone() + self.h.clone()
    }
}

Upvotes: 0

Views: 87

Answers (1)

malbarbo
malbarbo

Reputation: 11197

You can use the Copy trait to indicate that a type has copy semantics (instead of move semantics).

impl<T> Rect<T> where T: PartialOrd + Add<T, Output=T> + Copy {
    pub fn contains(&self, x: T, y: T) -> bool {
        x >= self.x && y >= self.y
            && x < self.x + self.w
            && y < self.y + self.h
    }
}

Can I count on the compiler that the clone() call will be discarded for numeric types, without any performance hit?

We hope that the compiler do this optimization, but there are no guarantees (thanks @DK).

There is an RFC to formalize the semantics of clone for Copy types. The RFC start with the following:

It's generally been an unspoken rule of Rust that a clone of a Copy type is equivalent to a memcpy of that type

Upvotes: 2

Related Questions