essay | tech | year-summary | about

返回上级菜单

Rust Ownership (3)


日期:2021-05-16T00:00:00Z

Slices Reference

◦Slice是一种类似于subarray的东西

◦不过不同之处在于,譬如js的slice是返回一个新的内存空间

◦Rust的slice是返回一个reference

Slice的必要性

考虑下面的一段代码,如果想返回部分文字列的话,是做不到的,只能返回坐标。然后根据坐标再在原来的文字列里面

fn first_word(s: &String) -> usize {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return i;
        }
    }

    s.len()
}
fn main() {
    let mut s = String::from("hello world");

    let word = first_word(&s); // word will get the value 5

    s.clear(); // this empties the String, making it equal to ""

    // word still has the value 5 here, but there's no more string that
    // we could meaningfully use the value 5 with. word is now totally invalid!
}
let s = String::from("hello world");

let hello = &s[0..5];
let world = &s[6..11];

let slice = &s[0..2];
let slice = &s[..2];

let slice = &s[3..len];
let slice = &s[3..];

let slice = &s[0..len];
let slice = &s[..];
fn main() {
    let mut s = String::from("hello world");

    let word = first_word(&s);

    s.clear(); // error!

    println!("the first word is: {}", word);
}
$ cargo run
   Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
  --> src/main.rs:18:5
   |
16 |     let word = first_word(&s);
   |                           -- immutable borrow occurs here
17 | 
18 |     s.clear(); // error!
   |     ^^^^^^^^^ mutable borrow occurs here
19 | 
20 |     println!("the first word is: {}", word);
   |                                       ---- immutable borrow later used here

error: aborting due to previous error

For more information about this error, try `rustc --explain E0502`.
error: could not compile `ownership`

To learn more, run the command again with --verbose.
fn first_word(s: &String) -> &str { 
    &s[..]
}

fn first_word(s: &str) -> &str {
    &s[..]
}
    
fn main() {
    let my_string = String::from("hello world");

    // first_word works on slices of `String`s
    let word = first_word(&my_string[..]);

    let my_string_literal = "hello world";

    // first_word works on slices of string literals
    let word = first_word(&my_string_literal[..]);

    // Because string literals *are* string slices already,
    // this works too, without the slice syntax!
    let word = first_word(my_string_literal);
}

other slices

let a = [1, 2, 3, 4, 5];

let slice = &a[1..3];

reference

The Slice Type