projects
/
rust-101.git
/ blobdiff
commit
grep
author
committer
pickaxe
?
search:
re
summary
|
shortlog
|
log
|
commit
|
commitdiff
|
tree
raw
|
inline
| side by side
implement rgrep, and write part 12 (draft) about it
[rust-101.git]
/
workspace
/
src
/
part04.rs
diff --git
a/workspace/src/part04.rs
b/workspace/src/part04.rs
index 4f2174ad8e5a9cf2c8dd8871189c00fc13e17366..bde913f20cf6b7750591c0bc3849daaaa09ea250 100644
(file)
--- a/
workspace/src/part04.rs
+++ b/
workspace/src/part04.rs
@@
-14,7
+14,7
@@
fn work_on_vector(v: Vec<i32>) { /* do something */ }
fn ownership_demo() {
let v = vec![1,2,3,4];
work_on_vector(v);
fn ownership_demo() {
let v = vec![1,2,3,4];
work_on_vector(v);
- /* println!("The first element is: {}", v[0]); */
+ /* println!("The first element is: {}", v[0]); */
/* BAD! */
}
// ## Shared borrowing
}
// ## Shared borrowing
@@
-23,7
+23,9
@@
fn vec_min(v: &Vec<i32>) -> Option<i32> {
use std::cmp;
let mut min = None;
use std::cmp;
let mut min = None;
- for e in v {
+ // This time, we explicitly request an iterator for the vector `v`. The method `iter` borrows the vector
+ // it works on, and provides shared borrows of the elements.
+ for e in v.iter() {
// In the loop, `e` now has type `&i32`, so we have to dereference it to obtain an `i32`.
min = Some(match min {
None => *e,
// In the loop, `e` now has type `&i32`, so we have to dereference it to obtain an `i32`.
min = Some(match min {
None => *e,
@@
-45,7
+47,7
@@
fn shared_borrow_demo() {
// ## Mutable borrowing
fn vec_inc(v: &mut Vec<i32>) {
// ## Mutable borrowing
fn vec_inc(v: &mut Vec<i32>) {
- for e in v {
+ for e in v
.iter_mut()
{
*e += 1;
}
}
*e += 1;
}
}
@@
-55,7
+57,7
@@
fn mutable_borrow_demo() {
/* let first = &v[0]; */
vec_inc(&mut v);
vec_inc(&mut v);
/* let first = &v[0]; */
vec_inc(&mut v);
vec_inc(&mut v);
- /* println!("The first element is: {}", *first); */
+ /* println!("The first element is: {}", *first); */
/* BAD! */
}
// ## Summary
}
// ## Summary