3.6 String 与 切片&str的区别

The rust String  is a growable, mutable, owned, UTF-8 encoded string type.

&str ,切片,是按UTF-8编码对String中字符的一个引用,不具有owned。

不具有owner关系,是非常非常重要的一区别,看下面代码

pub fn test1(){
    //"abc"是 &str 切片类型
    let s1 = "abc";
    let s2 = s1;
    //如果切片具体owner,则下面的语句必报错; 实际上下面的语句是可以正常运行的。
    println!("{}",s1);
    println!("{}",s2);
}


pub fn test2(){
    let s1 = String::from("abcd");;
    let s2 = s1;

    //由于s1的owner已经转移给s2,下面再使用s1则会报错
    // println!("{}",s1);
    println!("{}",s2);
}


pub fn test3(){
    let s1 = String::from("abcd");

    //取s1的切片则没有关系
    let s2 = s1.as_str();
    println!("{}",s1);

    println!("{}",s2);
}
原文地址:https://www.cnblogs.com/perfei/p/14085543.html