Error when using keyword 'crate' as parameter name [E0532]

I think crate is a common parameter name in some specific programs. I find it really weird to chance the parameter name to sth else...

Is this in some form still possible or do i really need to use another name for my parameter?

struct Stack {
    crates: Vec<Crate>
}

struct Crate {
    content: char
}

impl Stack {
    fn push(&self, crate:Crate) {
    }
}

Unresolved reference: crate
expected unit struct, unit variant or constant, found module crate [E0532] not a unit struct, unit variant or constant

I would use either crate_ or krate. Trying to use keywords as identifiers is really just exchanging one problem (this isn't the name I wanted to use) for a different one (this name is now hard to type).

Rust has a mechanism for "raw identifiers" which lets you write names that aren't otherwise valid... but Rust seems to make a special exception for crate:

fn main() {
    let r#crate = 42;
    println!("{}", r#crate);
}

Yields:

error: `crate` cannot be a raw identifier
 --> src/main.rs:2:9
  |
2 |     let r#crate = 42;
  |         ^^^^^^^

error: `crate` cannot be a raw identifier
 --> src/main.rs:3:20
  |
3 |     println!("{}", r#crate);
  |                    ^^^^^^^

It doesn't do this for other keywords like try or mod, so I think you're just flat out of luck. If I had to guess (and I do), I'd assume this is because of being able to use crate in paths like crate::some_mod::SomeType.

2 Likes

Seems to be the case:

1 Like

You should know what is an identifier in Rust

...
Identifiers may not be a strict or reserved keyword without the r# prefix described below in raw identifiers.

RAW_IDENTIFIER : r# IDENTIFIER_OR_KEYWORD Except crate, self, super, Self

A raw identifier is like a normal identifier, but prefixed by r# . (Note that the r# prefix is not included as part of the actual identifier.) Unlike a normal identifier, a raw identifier may be any strict or reserved keyword except the ones listed above for RAW_IDENTIFIER.

src: the Reference

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.