Are there Rust variable naming conventions for things like Option <T>?
I'm not sure if there is a convention for each of these, but I see (and use) often maybe
for Option
s. i.e.
let maybe_thing: Option<Thing> = ...
let thing: Thing = ...
Also, with regard to use, u
and user
in this situation, it is good to use user
in both places. i.e.
let user = match maybe_user {
Some(user) => user,
...
This is because the match expression will be evaluated prior to assignment let
.
However (slightly off topic) @Manishearth is correct, in this case it would be better to use or_else
. i.e.
let user = maybe_user.or_else(|| new("guest", "guest")).unwrap();
I would recommend checking out the rest of the Option
methods as they are great for shrinking the pattern match
.
source to share
If you are going to use a variable to initialize another, and you no longer need to use the first variable, you can use the same name for both variables.
let user = /* something that returns Option<?> */;
let user = match user {
Some(u) => {
u
}
None => {
new("guest", "guest").unwrap()
}
};
In the initializer for the second binding, the let
identifier is user
resolved to the first variable user
, not the one that is defined because it hasn't been initialized yet. Variables defined in a statement let
are entered only in the scope after the whole statement let
. The second variable user
overrides the first variable user
for the rest of the block.
You can also use this trick to turn a mutable variable into an immutable variable:
let mut m = HashMap::new();
/* fill m */
let m = m; // freeze m
Here the second let
has no keyword mut
, so it m
is not changed anymore. Since it shades too m
, you no longer have access to the variable m
(although you can add later let mut
to change it again).
source to share
First, your block match
can be replaced withoptional_user.or_else(|| new("guest", "guest")).unwrap()
Typically for destructions where the destructured variable is not used in a large block, the short type name is usually used u
. However, it would be better to call it user
if the block was large with many statements.
source to share