Last active
August 7, 2017 04:27
-
-
Save deepak/9d7fd0340d4e898ae32df97863d7b83f to your computer and use it in GitHub Desktop.
rust-slices.txt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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