Rust學習(12):slice

slice是String的一部分引用。類似切片。

字符串slice

slice獲取值的使用權但是沒有得到值得所有權

fn main() {
    let s = String::from("Hello world");

    let hello = &s[0..5]; //[start, end)
    let world = &s[6..11]; //[start, end);
    println!("{},{}", hello, world);

    let hello = &s[..5]; //[0, end)
    let world = &s[6..]; //[start, len);
    let string = &s[..]; //[0, len)
    println!("{},{}, {}", hello, world, string);


    let hello = &s[0..=4]; //[start, end]
    let world = &s[6..=10]; //[start, end]
    println!("{},{}", hello, world);
}

在這裏插入圖片描述

其他slice

fn main() {
    let a = [1, 2, 3, 4, 5];
    let slice = &a[1..3];   //類型是&[i32]

    
    println!("{}, {}", slice[0], slice[1]);
}

參考:https://kaisery.github.io/trpl-zh-cn/ch04-03-slices.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章