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);
}

 

切片转String

 let fil: String= "/tmp/hello.txt".to_string();
还有一个方法叫into_string(),多了一个in,in是进入的意思,let B = A.into_string();
就是A进到B里去了
在rust中就是ownership的转换,

首先, A得具有ownership,像切片这种类型本身是另外一个类型的片段数据,没有ownership,就没法用into_string这个方法
切片的传值、传参,只能是将自己指向的地址传递过去,让另外一个变量指向自己指向的地址,所有切片传参一定是这样的 aaa(&name),有一个&

然后,
let B = A.into_string();
调用之后,A就不能再用了,以后生效的只有B

它们的方法定义

to_string:

fn to_string(&self) -> String;

into_string:

fn into_string(self) -> String;
关于它们的不同,这里说的更详细

#[stable(feature = "box_str", since = "1.4.0")]
    #[inline]
    pub fn into_string(self: Box<str>) -> String {
        let slice = Box::<[u8]>::from(self);
        unsafe { String::from_utf8_unchecked(slice.into_vec()) }
    }

 

#[stable(feature = "rust1", since = "1.0.0")]
impl ToOwned for str {
    type Owned = String;
    #[inline]
    fn to_owned(&self) -> String {
        unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
    }

    fn clone_into(&self, target: &mut String) {
        let mut b = mem::take(target).into_bytes();
        self.as_bytes().clone_into(&mut b);
        *target = unsafe { String::from_utf8_unchecked(b) }
    }
}

 

字节数组转字符串
pub fn from_utf8_lossy(v: &[u8])


posted @ 2020-12-04 14:13  方诚  阅读(270)  评论(0编辑  收藏  举报