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()
}
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.
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.
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).