From: Ralf Jung Date: Mon, 22 Jun 2015 11:39:08 +0000 (+0200) Subject: Java actually doesn't do pointer checks all the time X-Git-Url: https://git.ralfj.de/rust-101.git/commitdiff_plain/1b77423cf168e5ff2b41667ea67252f4fbc44652 Java actually doesn't do pointer checks all the time --- diff --git a/src/part04.rs b/src/part04.rs index e4c6a59..14deb89 100644 --- a/src/part04.rs +++ b/src/part04.rs @@ -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` diff --git a/src/part07.rs b/src/part07.rs index a996a22..65d6823 100644 --- a/src/part07.rs +++ b/src/part07.rs @@ -27,9 +27,7 @@ pub fn vec_min(v: &Vec) -> Option<&T> { // Notice that the return type `Option<&T>` is technically (leaving the borrowing story aside) a // pointer to a `T`, that could optionally be invalid. In other words, it's just like a pointer in // C(++) or Java that can be `NULL`! However, thanks to `Option` being an `enum`, we cannot forget -// to check the pointer for validity, avoiding the safety issues of C(++). At the same time, when we -// have a borrow like `v` above that's not an `Option`, we *know* that is has to be a valid -// pointer, so we don't even need to do the `NULL`-check that Java does all the time.
+// to check the pointer for validity, avoiding the safety issues of C(++).
// Also, if you are worried about wasting space, notice that Rust knows that `&T` can never be // `NULL`, and hence optimizes `Option<&T>` to be no larger than `&T`. The `None` case is represented // as `NULL`. This is another great example of a zero-cost abstraction: `Option<&T>` is exactly like