Sitemap
Better Programming

Advice for programmers.

Rust: Singleton Application

Borrow checker vs design patterns

4 min readMay 17, 2022

--

Hi everyone. Let’s talk about one of Rust's concepts that make Rust developers go crazy: the Borrow checker.

Press enter or click to view image in full size
Foto de Michael Dziedzic en Unsplash

But first, let me explain what this is and why you should be interested in this topic if you want to start to develop in Rust.

In other compiled languages, such as C++, you must control memory, i.e., allocate and free dynamic memory. In others like Java, you don’t face this problem because a garbage collector is running and listening for unused memory to free it in the background.

Rust makes it “simpler” or makes it seem simpler, because when a scope is terminated, Rust frees it. Also, when you pass the value to a function/method (another scope), this scope gets the variable property, and when its scope terminates, this memory is freed again. Let’s see an example:

Therefore, if we want to reuse some_string in these functions, we have to switch to get a reference instead of the variable's value in the print function.

Or return the value again to not free it.

There are other rules with the borrow checker that can raise an error. For example, when passing a reference to a struct constructor, the borrow checker will raise an error because it doesn’t know how long the struct or the variable you pass as a reference can live, so the compiler will force you to use lifetime. But, beware, this is a trap.

Borrow checker is the guard to avoid memory leaks

We can say the borrow checker is the guard to avoid memory leaks that make you debug for hours to find out the occasional bug.

Design Patterns

There are some design patterns, such as Singleton, that the borrow checker might hinder. This is because, in the Singleton strategy, you must store an instance of the structure as static in the structure.

Singleton is responsible for storing a global instance of itself and being reused by the entire application to store global variables such as configurations or connections to a service.

In theory, the singleton works like this. We create a class/struct with an attribute to itself and a method that creates an instance of itself and returns it.

Spoiler: Rust doesn’t let you create this for two reasons:

  • You can’t use an attribute from a struct without instantiating.
  • The borrow checker won’t let you store an instance of itself because it detects it as a memory leak.

That’s why Rust core developers design some tools for this.

Reference Counted (aka Rc) struct

This structure allows you to share references between different domains by means of a weak reference. How does it work?

This makes the code compile because the Rc structure creates a weak reference as an attribute that tells the compiler that it doesn’t need to check at compile time. The problem is we aren’t using this attribute after creating it. So, in the next call, it will create it again.

Get Ángel Berhó’s stories in your inbox

Join Medium for free to get updates from this writer.

However, we can use this tool to structure data as a dynamic list, but not as a Singleton.

This only works in a local thread. If you need more threads, I recommend you use Arc. This trait implements the Clone trait to clone references with threadsafe.

Mutex

It will store our value as mutable but will block the resource until someone leaves the reference to this value. For example, if we have a variable of type u8, it will make it mutable even though it is a primitive type.

So, why is it still not getting the actual value? Well, in the get_instance we are instantiating the Singleton structure each time we call it and not using our actual instance attribute. So, we have to get from any global state.

What’s the problem? Static variables can’t be mutable because Rust believes you can create race conditions, and so it forces you to use unsafe scope.

thread_local!

This macro allows the creation of static variables without a non-constant value treatment. Here’s an example:

#[derive(Default)]

This derive makes our struct implement the Default trait. The trait implements the primary and non-primary default values of Rust. So, we don’t have to worry about defaults now.

thread_local! {
static SINGLETON_POOL: Arc<Singleton> = Arc::new(Default::default());
}

Creating a static default value of our Singleton. In addition, we have changed Rc to Arc (Atomic Reference Count), which allows us to clone the reference.

pub fn get_instance() -> Arc<Singleton> {
SINGLETON_POOL.with(|singleton_pool| singleton_pool.clone())
}

The get_instance method now returns a global state of the Singleton. And voilà, we got our singleton working.

Conclusion

It is not a good idea to create a Singleton as other languages do. Perhaps it could be simpler to store the variable in the parent state and share it among the components that need this configuration. For example, the Actix web framework implements a state that will be passed in each request.

Resources

Thanks for reading; I hope you like it! I’d love to hear your thoughts and experiences working with design patterns or Rust.

Leave a comment or contact me on LinkedIn.

--

--

Ángel Berhó
Ángel Berhó

Written by Ángel Berhó

I like to discover new technologies and share with others. #Python #Js #Rust I’m software Engineer @ World