【问题标题】:Are strings Drop or Copy?字符串是删除还是复制?
【发布时间】:2017-11-17 15:22:43
【问题描述】:

我正在了解 Rust 的所有权。我的测试表明,在移动 String 实例时,会在变量赋值上复制字符串文字。这是否意味着StringDrop 而字符串文字是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's 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's ok,
}

fn test_tuple_assign() {
    let pa = (1, 2);
    let pb = pa;
    println!("pa = {:?}, pb = {:?}", pa, pb); // it's 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();
}

使用rustc variable_assign_test.rs -o a.out 编译并使用./a.out 运行

如果test_tuple_assign() 的最后一行未注释,则会为变量eric 得到错误value used here after move

【问题讨论】:

  • 谢谢,我觉得你的问题比较容易理解:)

标签: rust ownership


【解决方案1】:

是的

需要明确的是,所有不可变引用 (&T) 都是 Copy,而可变引用 (&mut T) 只能移动。 &'static str,字符串字面量的类型,只是 &T 的一种特例,一个不可变的引用,因此是 Copy

另一方面,String 实例是为其内容动态分配的缓冲区的唯一所有者。这可以防止它成为Copy(单一所有者)并要求它实现Drop(以释放动态分配的缓冲区)。

不过,详细地说,String 并没有直接实现Drop,而是一个封装在Vec<u8> 上的封装,而Vec<u8> 本身实现了Drop。行为是相同的,只是StringDrop 实现是自动生成的,而Vec<u8> 的实现是manually written

【讨论】:

    猜你喜欢
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 2015-09-30
    • 1970-01-01
    • 2015-08-13
    • 2022-09-25
    • 1970-01-01
    相关资源
    最近更新 更多