Wishful Coding

Didn't you ever wish your
computer understood you?

My girlfriend in Rust

Some people don’t like to say “my girlfriend”. They think it implies ownership over the person. Lets explore that using Rust. Swap genders at will.

struct Human {
    name: str
    // ???
}

Even though Rust is not object oriented, I’m sorry for objectifying Alice here.

let bobs_girlfriend = Human { name: "Alice", /* ??? */ };

This is what some people think when they hear “my girlfriend”, Bob owns Alice in this cenario.

let charlies_friend = &bobs_girlfriend;

Charlie can only borrow Alice, Bob maintains ownership of Alice, the compiler enforces monogamy.

That is not how it works, lets try again.

use std::rc::Rc;
use std::option;

let alice = Rc::new(Human { name: "Alice", /* ??? */ });

The name “Alice” refers to Alice, who is now owned by the reference counter. In this digital world it’s like a god, it decides who lives and dies.

let mut bobs_girlfriend = Some(alice.clone());

“Bobs girlfriend” is a reference to Alice, no more or less than the name “Alice”. Bob owns the reference, but not Alice.

assert!(*alice == *(bobs_girlfriend.unwrap()));

“Alice” and “Bobs girlfriend” are the same thing, though the latter is mutable and optional.

assert!(*(bobs_girlfriend.unwrap()).beautiful == true);

This throws a compiler error; Beauty is in the eye of the beholder.

let mut charlies_girlfriend = Some(alice.clone()); // Polygamy

Charlie does not own Alice either.

charlies_girlfriend = None
bobs_girlfriend = None

If you are forgotten, do you cease to exist? Better not find out. Love the ones dear to you. You’ll never know when they will be garbage collected.

Published on