avoid using std::cmp::min, for it doesn't support f32...
[rust-101.git] / src / part04.rs
index 0ecfe76e53f1eaaa837d5f60fe9b130d9e9dc927..663e01e8257b795f856e58c2bdffc1da64a7166e 100644 (file)
@@ -1,8 +1,6 @@
 // Rust-101, Part 04: Ownership, Borrowing
 // =======================================
 
-use std::cmp;
-
 // Rust aims to be a "safe systems language". As a systems language, of course it
 // provides *references* (or *pointers*). But as a safe language, it has to
 // prevent bugs like this C++ snippet.
@@ -67,6 +65,8 @@ fn ownership_demo() {
 // I also took the liberty to convert the function from `SomethingOrNothing` to the standard
 // library type `Option`.
 fn vec_min(v: &Vec<i32>) -> Option<i32> {
+    use std::cmp;
+
     let mut min = None;
     for e in v {
         // In the loop, `e` now has type `&i32`, so we have to dereference it to obtain an `i32`.
@@ -86,10 +86,10 @@ fn shared_borrow_demo() {
     vec_min(&v);
     println!("The first element is: {}", *first);
 }
-// What's going on here? First, `&` is how you create a shared borrow to something. This code creates three
-// shared borrows to `v`: The borrow for `first` begins in the 2nd line of the function and lasts all the way to
-// the end. The other two borrows, created for calling `vec_min`, only last for the duration of that
-// respective call.
+// What's going on here? First, `&` is how you create a shared borrow to something. All borrows are created like
+// this - there is no way to have something like a  NULL pointer. This code creates three shared borrows to `v`:
+// The borrow for `first` begins in the 2nd line of the function and lasts all the way to the end. The other two
+// borrows, created for calling `vec_min`, only last for the duration of that respective call.
 // 
 // Technically, of course, borrows are pointers. Notice that since `vec_min` only gets a shared
 // borrow, Rust knows that it cannot mutate `v` in any way. Hence the pointer into the buffer of `v`
@@ -129,7 +129,8 @@ fn mutable_borrow_demo() {
 // they do. However, the `v` in `mutable_borrow_demo` is not actually usable, it is not *active*: As long as there is an
 // outstanding borrow, Rust will not allow you to do anything with `v`.
 
-// So, to summarize - the ownership and borrowing system of Rust enforces the following three rules:
+// ## Summary
+// The ownership and borrowing system of Rust enforces the following three rules:
 // 
 // * There is always exactly one owner of a piece of data
 // * If there is an active mutable borrow, then nobody else can have active access to the data