How come len() knows all these strings?

In the code below I used a for and found the space based on the byte literal. Then I return the position of the space which is the index i.

But why can len() know the length of the string from index 0 to the position of the space. Even though I only return the position of the space only.

fn main() {
    let mut x = String::from("halo ola");
    let hasil = kata_pertama(&x);

    x.clear();

    println!("{}", hasil)
    }
fn kata_pertama (x: &String) -> usize {
    
    let x = x.as_bytes();
    
    for (i, &item) in x.iter().enumerate(){
     
        if item == b' '{
            return i
        }
    }
    
    x.len()
}

I really appreciate your answer, thank you.
Qori.

The x.len() line is only ever reached if no space is found. It then returns the position of the end of the string, which equals the length of the whole string.

If a space is found however, the function exits via an early return in the line return i. This then returns the index i that comes from the enumerate() iterator, which is the index in the iterator (which is an iterator over bytes, hence it also is a bytes index) of the current byte that turned out to be a space character.

3 Likes

After making this question I thought and scribbled on the book. I just thought about it after doing that and reading in more detail rust docs. With your answer, my opinion is more convincing. Thank You.

If you want to write your function in a shorter fashion, using pre-existing API from the standard library, you could write it as something like

fn kata_pertama(x: &str) -> usize {
    x.find(' ').unwrap_or(x.len())
}

Note that using &str instead of &String in function arguments is common practice as it makes the function more versatile (supporting other kinds of values like string literals, or Arc<str>, or slices referring to part of a String, etc…), without any real downsides (&String can implicitly coerce into &str in Rust).

5 Likes

Thank you.
May your day be filled with luck.

1 Like

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.