Architecture, Rust, Software Development

Can we use a Layered Architecture Pattern in Rust?

Can we use a layered architecture pattern in a Rust codebase? Like using controller, service, and persistent layers? Yes, we can, but we may need to implement it slightly differently than in most programming languages like Java, C#, etc. How we implement the pattern may also depend on the Rust web framework we use. Rust enforces programming safety at the compiler level, particularly for memory safety. Therefore, coding-wise, we need to align with what the programming language allows and prohibits.

Rust Forces Us To Think (Harder)

Rust forces us to think harder when programming unless we know Rust like the back of our hand. Rust enforces memory safety. To achieve that, Rust introduces a new paradigm in programming. Therefore, how we usually code and think in other languages may not work in Rust.

A layered architecture pattern in Rust is a sound choice to start with

Although some people label Rust a systems programming language, we can use it to create business applications. Also, there are web frameworks available for Rust that will help us in our development effort. These Rust web frameworks include Actix-Web and Rocket.

Business applications do not resemble tools, system programs, or device drivers, which are usually very technical in coding.  Meanwhile, the codes in business applications must be easier to understand and properly organized.

A simple example of using a layered architecture pattern in Rust is as follows, using Rocket.

As we can see, we have a decent codebase organization which is something we should always have in business applications. With Rocket, our main function may look similar to the following codes.

Then, our request handler looks like the following codes to handle specific HTTP requests.

Now it is apparent that our database connections come from some pool from the web framework. See the following posts.

Implementing a layered architecture pattern may mean pushing that database connection to the persistent layer. Then, we invoke SQL commands in that bottom layer.

If this is acceptable, then, by all means, proceed with a layered architecture pattern in Rust.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like