Skip to content

Instantly share code, notes, and snippets.

@deepak
Last active August 7, 2017 04:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deepak/9d7fd0340d4e898ae32df97863d7b83f to your computer and use it in GitHub Desktop.
Save deepak/9d7fd0340d4e898ae32df97863d7b83f to your computer and use it in GitHub Desktop.
rust-slices.txt
fn main() {
let mut s = String::from("hello world");
let len = first_word(&s);
{
let word = &s[0..len];
println!("word is {}", word); // word is hello
}
s.clear();
let word = &s[0..len]; // thread 'main' panicked at 'byte index 5 is out of bounds of ``', src/libcore/str/mod.rs:2144
println!("word is {}", word);
}
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 len = first_word(&s);
// let word = s[0..len]; // `str` does not have a constant size known at compile-time
let word = &s[0..len];
println!("word is {}", word);
// s.clear(); // Error! mutable borrow occurs here and let word = &s[0..len] is immutable
}
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()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment