Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
fn main() {
let s = String::from("hello");
let c = s[0];
println!("{c}");
}It does not compile
- Expecting
h, as in Python or JavaScript: a RustStringtakes no numeric index, ands[0]stops the build with E0277. - Expecting the first byte, 104: bytes come from
s.as_bytes()[0]ors.bytes(), never from indexing theStringitself.
- How would you get the first character of
sas anOption<char>? - Which kind of index does a
Stringaccept, and when does it panic?