#how to implement Copy on a struct with a Vec

1 messages · Page 1 of 1 (latest)

signal nymph
#

I have a struct that looks like this. How can i implement Copy on it? the only way i can see is to 1. make params and returns borrows, but then i need to a lifetimes everywhere and rewrite the 90% of my project. Or 2. turn the Vecs to arrays and limit the length, which i don't really want to do.

#[derive(Debug, PartialEq, Clone, Copy)]
pub struct FuncPtr {
    pub ptr: usize,
    pub params: Vec<TypeLiteral>,
    pub returns: Vec<TypeLiteral>
}
chilly kettle
#

How can i implement Copy on it?
You can't.

#

You can, however, stick to Clone and call.clone() where needed

#

Copy represents a "dumb" bitwise copy: it copies the bits of the thing you have on hand. This is fine for, say, u32, but not for Vec: in the latter's case, the thing you're holding is just a (ptr, len, capacity) struct, the actual data is behind the pointer

#

Duplicating that struct would not duplicate the actual data

#

And it would lead to two vecs that both think they own it, which can trivially lead to things like use after free or double free

#

.clone(), on the other hand, also copies the actual data

pulsar zenith
#

You'll have to turn them into arrays.

#

There are crates for stack based, size limited Vecs that can improve the ergonomics.

chilly kettle
#

ArrayVec is still not Copy though

#

It has to be Drop, and Drop is mutally exclusive with Copy

signal nymph
#

think ill just remove Copy and spam .clone() everywhere. not pretty but that's the rust life 😎 . Ty anyway