About `const`s copying

#1

I have a question regarding constants.
Does a constant allow to copy a type that does not implement Copy?
What I mean is that if I do something like this (I think) am performing a copy of a type that does not implement Copy form the code memory to the stack, and that type may be complex.
Am I wrong?

1 Like
#2

const in Rust is #define in C. In your code cent1 is re-constructed every time when you refer it.

2 Likes
#3

Yep, that’s it. Whenever a const variable is mentioned (its identifier is used as a value expression), it is built as a local, thus “copying from code memory”.

As @Hyeonu said, there is almost no difference between:

const X: T = ...;


fn main ()
{
     let x = X;
}

and

macro_rules! X {() => (
    ...
)}

fn main ()
{
     let x = X!();
}

except for one thing: the latter accepts any kind ..., whereas the former requires that ... be a const expression (e.g., a [tuple] struct literal with const fields, or a call to a const fn), precisely to ensure that the initialisation of the local x boils down to directly writing mem::size_of::<T>() bytes and avoids calling functions at runtime.

1 Like