Formating for const

Const used to be mostly for global values, but with the current const improvement, the places where they can be used has increased a lot and I have the feeling the current formatting rules does not fit anymore.

For me the main interest of the current use of screaming case on constant is to distinguish global variables. But with const improvement, a lot of the constant will be local, so we loose this particularity. I know we can already use const locally, but it nearly never happens, even the name of the warning when you use low case on a local const is non_upper_case_globals.

Since there is not really a huge difference in the way you use a local const and a immutable variable, the different notation is really disturbing to me.

Another problem is that generics are usually one long. One letter types parameter and one letter const parameter are indistinguishable.

So i propose to change the current rule to request screaming case only on global variables, local variables should be snake case, even if they are const.

3 Likes

Note that local constants still behave like items, and not like locals.

fn main() {
    println!("the answer: {}", THE_ANSWER);
    const THE_ANSWER: u32 = 92;
}

playground

10 Likes

An alternative solution to that is to stop recommending single letter generic names.

When there's something semantically meaningful to a generic, I try to give it a meaningful name (e.g. fn fold<Acc, Fold> instead of fn fold<B, F>). Even without having const N in the mix, I've found this increases reachability.

4 Likes

I still think local constants should use all-caps, to distinguish them at the site of usage.

They also behave differently in match arms.

fn main() {
    const CONST: u32 = 100;
    let not_const: u32 = 50; // not used
    match 75 {
        CONST => println!("CONST is {}", CONST), // only matches 100
        not_const => println!("not_const is {}", not_const), // always matches
    }
    match 100 {
        CONST => println!("CONST is {}", CONST), // only matches 100
        not_const => println!("not_const is {}", not_const), // always matches
    }
}

playground

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.