Why this var still have a value after var.clear()?

Because word isn’t connected to the state of s at all, word still contains the value 5.

Why is it said like that, even though word is a reference to s, does this happen because the value of String becomes usize? but if so how come we can still delete String.

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

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


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!


the return type of your first_word function is an owned type, not a reference to the string that you passed to it as an argument.


Neither s nor &s "become" usize. A reference to s (i.e. &s) is passed to first_word. first_word uses the data reachable to produce and return a usize. After that, the usize exists independently of s or &s.

You never gave away ownership of s (you passed a reference, &s) and there are no outstanding borrows of s after the call to first_word returns. So you're free to call clear on s, which requires an exclusive reference (&mut self). word is unaffected.

word isn't "totally invalid", it's still 5. For all the compiler can tell, you still need to know that for some reason. Maybe you're in an I/O loop calculating the longest first word of some stream of lines, with no need to hold on to the entire contents of the stream.

If you do logically require word to always be a valid index into s, well, that's on you -- there's no way Rust or any other language can read your mind to prevent logic errors. Languages generally interpret code consistently and predictably,[1] not by guessing your higher level logic.

  1. and it's annoying when they fail to do so ↩︎


Thank you, clear.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.