Are lines flushed or copied?

I am learning about Rust property. My tests show that string literals are copied when assigning variables and instances are String

moved around. Does this mean that String

- Drop

whereas string literals Copy

?

variable_assign_test.rs

// variable assign test,

// assign variable on stack to another,
fn test_stack_assign() {
    let x = 5;
    let y = x; // data duplicated on stack,
    println!("x = {}, y = {}", x, y); // it ok,
}

// assign variable on heap to another,
fn test_heap_assign() {
    let s1 = String::from("hello");
    let s2 = s1;    // now s1 is invalid, should not use it any more,
    // println!("{}", s1); // this won't compile,
    println!("s2 = {}", s2); // it ok,
}

fn test_tuple_assign() {
    let pa = (1, 2);
    let pb = pa;
    println!("pa = {:?}, pb = {:?}", pa, pb); // it ok,

    // tuple that contains string literal,
    let name_monica = "monica";
    let monica = (11, name_monica);
    let monica2 = monica;
    println!("monica = {:?}, monica2 = {:?}", monica, monica2);

    // tuple that contains String instance,
    let name_eric = String::from("eric");
    let eric = (12, name_eric);
    let eric2 = eric; // eric is invalid now,
    // println!("eric = {:?}, eric = {:?}", eric, eric2); // this won't compile,
}

fn main() {
    test_stack_assign();
    test_heap_assign();
    test_tuple_assign();
}

      

Compile with rustc variable_assign_test.rs -o a.out

and run with./a.out

If the last line is test_tuple_assign()

uncommented, it will get an error value used here after move

for the variable eric

.

+3


source to share


1 answer


Yes .

To be clear, all immutable ( &T

) references are Copy

, whereas volatile ( &mut T

) only move. &'static str

, the type of string literals is only one special case &T

, an immutable reference, and therefore Copy

.



On the other hand, the instance String

is the sole owner of the dynamically allocated buffer for its contents. This prevents it Copy

(single owner) and requires it to implement Drop

(to free the dynamically allocated buffer).

In detail, however, it String

does not implement Drop

directly, but instead is a wrapper Vec<u8>

that implements itself Drop

. The behavior is identical, it is just that the implementation is Drop

String

automatically generated and one Vec<u8>

is manually written .

+9


source







All Articles