Idiomatic naming when a name clashes with a keyword

Let's say that the ideal name for the variable is impl. You can't chose this name, as it is a keyword. What would be the second-best choice, and why?

  1. add _: impl_
  2. mutate the name: imp, krate
  3. use raw idents: r#impl
  1. Come up with a different name altogether.

If the name is part of a public api, 4 is the best option, 2 is okay in the case of imp (because imp and impl are both reasonable abbreviations of "implementation"), but not in the case of krate (which, assuming the codebase uses English, isn't a word). If it's internal, I'd say imp > my_impl > krate > r#impl > impl_. But those are all my own personal sense of aesthetics. I don't think there's a community consensus on it.

Tell this to rustc folks :yum:

1 Like

https://doc.rust-lang.org/edition-guide/rust-2018/module-system/raw-identifiers.html

This feature is useful for a few reasons, but the primary motivation was inter-edition situations.

It seems raw identifiers feature is (primarily) intended to be used when the new Rust edition introduces keywords which are used as identifiers in already existing code base.
It is primarily a feature to keep things compatible.

I don't know it is recommended to be used casually or not, but I don't like introducing identifiers to my code which are already known as keywords.
In other words, I prefer imp or impl_ to r#impl, and ty or type_ to r#type.

1 Like

Ah nice, I was just about to ask this question.

I usually lean towards #2 (krate), for no particular reason. My pet peeve is type – my code is littered with variables named typ :confused: I sometimes wish Rust used contextual keywords but I understand why it doesn't.

This is the sort of tiny opinionated thing I think would be good to standardize on, for the same reason rustfmt exists. (For precedent, Python made a decision about this in PEP 8, search for "avoid conflicts"). The decision should be added to the API Guidelines, and then eventually clippy could warn if you use krate or crate_ where the other form is preferred.

1 Like

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