Struct containing reference to slice does not implement copy
⚓ Rust 📅 2026-03-08 👤 surdeus 👁️ 4Hello,
I'm currently struggle with implementing Copy for a struct containing a reference. It seems to have an implicit bound on T being Copy which I don't understand since I'm only working with references and not with T itself.
The struct is defined like this:
#[derive(Eq, PartialEq, Copy)]
struct SmartSlice<'a, T> {
slice: &'a [T]
start: usize,
end: usize
}
which I use in a method like this:
pub fn merge(&self, other: &SmartSlice<'a, T>) -> SmartSlice<'a, T> {
// ...
if other.is_empty() {
return *self;
// ERROR: cannot move out of `*other` which is behind a shared reference [E0507]
// move occurs because `*other` has type `SmartSlice<'_, T>`, which does not implement the `Copy` trait
}
// ...
}
Why does the compiler require T to be copy here?
Shouldn't references always implement copy (since it's only a reference) and shouldn't therefore my struct also implement copy (without any bound on T implementing Copy) since it only works with references and never copies T itself?
I also tried adding a Self: Copy bound to the method, but if I use it with where T=String I get the following error when I try to call the method:
Trait
Copyist not implemented for "String"
which is clear, but still I'm only working with references to String and not with String itself, i.e. the value wouldn't be copied by the operation above.
3 posts - 3 participants
🏷️ Rust_feed