Skip to content

Redundant type specification in const definitions #37950

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
JinShil opened this issue Nov 23, 2016 · 5 comments
Closed

Redundant type specification in const definitions #37950

JinShil opened this issue Nov 23, 2016 · 5 comments

Comments

@JinShil
Copy link

JinShil commented Nov 23, 2016

The following const expression appears unambiguous...

struct BitField (u8, u8);

const BITFIELD = BitField(7, 0);   //  error: expected `:`, found `=`

fn main() { 
    println!("{}", BITFIELD.0);
}

...but to get it to compile, the type must be redundantly specified

struct BitField (u8, u8);

const BITFIELD: BitField = BitField(7, 0);  // OK, but "BitField" is redundant

fn main() { 
    println!("{}", BITFIELD.0);
}

Fixing this seems in line with the Rust 2017 Roadmap item, explicit types on statics and constants

Interestingly, this works fine...

struct BitField (u8, u8);

fn main() { 
    let bit_field = BitField(8, 0);   // No redundant type specification
    println!("{}", bit_field.0);
}

...so, the grammar appears inconsistent.

@sinkuu
Copy link
Contributor

sinkuu commented Nov 23, 2016

This problem is discussed in rfcs repo. rust-lang/rfcs#1349
It seems like globals require explicit type signatures for the same reason as functions (which is by design), though.

@est31
Copy link
Member

est31 commented Nov 23, 2016

I think it would be very bad if the type of a const would depend on where its used inside the crate (or even worse where its used outside of the crate).

@eddyb
Copy link
Member

eddyb commented Nov 23, 2016

@est31 That's not their point, but rather that the initializer expression is already fully typed.

Unlike functions, global constants and statics have their values exposed, so the type being deduced wouldn't be too far of a stretch - it is, however, not possible to implement at the moment.

@est31
Copy link
Member

est31 commented Nov 23, 2016

@eddyb allowing they types of constants to be derived when the initializer expression is fully typed would still mean that there is an "inconsistency" to what let does. I agree that in this particular example it is silly to have to specify the type though.

@steveklabnik
Copy link
Member

Yes, this is being tracked by rust-lang/rfcs#1349. Thanks @JinShil !

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants