Skip to content

ch04-03: String Slices, explain non-lexical lifetimes #1939

Closed
rust-lang/rust
#87503
@owenthereal

Description

@owenthereal

Trying to follow the example in the String Slices section:

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

    let word = first_word(&s);

    s.clear(); // error!

    println!("the first word is: {}", word);
}

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

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

    &s[..]
}

If I remove the line that makes use of to word (println!("the first word is: {}", word);), the compilation error as the following

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

goes away. This doesn't make sense because I would expect regardless word is used or not, s.clear() should yield the same compilation error. That makes me wonder whether there's a bug in the rust compiler. If this is expected, it would worth explaining more.

See the playground code for compilation error and the one without compilation error that has no word reference removed

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions