In my Rust journey I still discover some less known gems. Today's hero is use
. In most programming languages it is responsible both for reaching to some code and bringing it into the scope. In Rust this functionality is divided between mod
and use
- mod
makes something visible, use
shortens the call by creating local bindings.
That brings us to enums
. A lot of my code looked like this:
enum SomeLongAndDescriptiveName {
Foo,
Bar
}
fn main() {
let a = SomeLongAndDescriptiveName::Foo;
match a {
SomeLongAndDescriptiveName::Foo => (),
SomeLongAndDescriptiveName::Bar => (),
}
}
In order to shorten it use
can be used to locally bind enum members:
enum SomeLongAndDescriptiveName {
Foo,
Bar
}
use SomeLongAndDescriptiveName::*;
fn main() {
let a = Foo;
match a {
Foo => (),
Bar => (),
}
}
That instantaneously made my code much more readable. Especially when using alternatives Foo|Bar
syntax in match
or joined if let
statements from Rust 1.88.
Note 1: When using enum
from some other module if you need both enum
type and enum
variants it looks like this:
mod other;
use other::SomeLongAndDescriptiveName::{self, *};
fn flip ( x: SomeLongAndDescriptiveName ) -> SomeLongAndDescriptiveName { // enum type
match x {
Foo => Bar, // enum variant
Bar => Foo
}
}
Note 2: You can rename everything if needed, including variants:
mod other;
use other::SomeLongAndDescriptiveName::{self as E, Foo as F, Bar as B};
fn flip ( x: E ) -> E {
match x {
F => B,
B => F
}
}
So if you come to Rust from some other language with "classic" use
semantic don't be afraid to use use
more frequently for convenience/readability binding.
Top comments (0)