Are there Rust variable naming conventions for things like Option <T>?

Is there a naming convention for variables in the following cases: I feel like I have two names, one optional and one for expandable.

let user = match optional_user {
    Some(u) => {
        u
    }
    None => {
        new("guest", "guest").unwrap()
    }
};

      

+3


source to share


3 answers


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

.

+2


source


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).

+3


source


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.

+2


source







All Articles