(for JS developers?)
Also pointers to guides, docs, etc
https://github.com/rust-lang/meeting-minutes
If you want to know whats going on
https://github.com/rust-lang/rfcs
Invasive language changes need to go through the RFC process. Some are *really* well written and you can learn a lot about API design and programming in general by reading some.
struct Size {
rows: u32,
cols: u32
}
enum Step {
N, E, S, W
}
impl Step {
fn apply(&self, Size{rows, cols}: Size, index: u32) -> Option<u32> {
match *self {
N if index >= cols => Some(index - cols),
E if (index + 1) % cols > 0 => Some(index + 1),
S if index + cols < rows * cols => Some(index + cols),
W if index % cols > 0 => Some(index - 1),
_ => None
}
}
}
// simplified!
fn apply_path(size: Size, steps: &Vec<Step>) -> Result<u32, u32> {
let mut index = start;
for (i, step) in steps.iter().enumerate() {
match step.apply(size, index) {
// valid move, to new index i
Some(newindex) => {
index = newindex;
},
// invalid move
None => {
return Err(i + 1)
}
}
}
Ok(steps.len())
}
// fails:
let input = file.read_to_string().unwrap().as_slice().words();
../boilerplate.rs:57:16: 57:46 error: borrowed value does not live long enough
../boilerplate.rs:57 let input = file.read_to_string().unwrap().as_slice().words();
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../boilerplate.rs:52:35: 59:4 note: reference must be valid for the block at 52:34...
...
../boilerplate.rs:57:4: 57:65 note: ...but borrowed value is only valid for the statement at 57:3;
consider using a `let` binding to increase its lifetime
../boilerplate.rs:57 let input = file.read_to_string().unwrap().as_slice().words();
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error
// works:
let slice = file.read_to_string().unwrap();
let input = slice.as_slice().words();
Problem is this:
`.words()` takes a reference (pointer to a string buffer) and returns
an Iterator of references into that buffer (pointers)
But the buffer (read_to_string()) does not live long enough,
because it is not bound to a variable.
A variable binding (and its lexical scope) would define its lifetime,
that’s what the compiler says.
But (1) you have to understand what the compiler is actually telling you
and (2) you still don’t get it why the compiler can’t just *do the right thing*
try it yourself!