Rust: Notes on Ownership II

Alex Alonso
3 min readMar 21, 2021

Borrowing

Borrowing is what happens when a reference is passed as parameter to a function. When s goest out of scope in the end of calculate_length_borrow function, s reference is not dropped, because calculate_length_borrow doesn’t have ownership of it. This way, the variable s1 can be used after the function call.
Note that a borrowed value is immutable inside the function.

Mutable References

In order to be able to mutate a value passed as parameter, we have to assign that variable as mutable, using the mut keyword, pass a mutable reference using &mut s1 and declare the parameter as a mutable reference type, using &mut String . Like this:

The mindset here is the protection of data races from happening. Having two mutable references to the same data can be dangerous, as in this scenario, there would be multiple points where the data can be altered, but none of these guarantee data sync on the other points.

Taking that into account, there cannot be a mutable reference when there is an immutable one already. Wait what?
Having immutable and mutable reference at the same time means that the immutable data can change suddenly and unexpectedly.
Having said that, this won’t compile

Won’t Compile!

But his will, because the compiler is smart enough to know that the immutable “safe” references are used *after* the mutable “unsafe” one, and so no surprise can happen here.

Ok, no mutations after line 6…

Dangling References

Won’t compile!

A dangling reference is a pointer to a space in memory that has been assigned to another pointer. For whatever reason, is a “lost” pointer, that will access data that it doesn’t manage and that has been changed by another context. Causing the program to bzzaaaaboopboom.

This can be solved by moving the ownership of s out!

Transfering the ownership of s

Slices

From my understanding, slices are references to parts of a value. Taking a string slice as an example:

let s = String::from(‘hello world’);
let slice = &s[0..4] // reference to ‘hello’
// then some mutation happen… s becomes ‘whale world’
// slice references to ‘whale’

This is useful because we could store the actual value from the string, and when the string mutated, an invalid value would reside at slice. An outdated one. So storing the slice is a better way to go in this case.

There are also array slices too:

Array slices

--

--