Global constants vs associated constants #3992
-
I noticed that through our codebase we mostly use global constants. Since Rust 2017 there are associated constants, which work kinda like public static final members in Java classes. I think they offer better structuring and less cluttering of global namespace. I propose to use them moving forward when constant you want to introduce have some clear type logically associated with it, and, probably, even refactor older constants that are similar in the same go What do you think? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
I am all for the better code, and associated constants are a great way to structure the related entities. Let's use them where applicable 👍 |
Beta Was this translation helpful? Give feedback.
-
👍, with a caveat. Caveat: Rust's primary units of encapsulation are a module and a crate, so generally it's perfectly fine to have stuff in module namespace. It is not a problem by itself. Often, the opposite is true -- people needlessly put stuff in impl blocks. So, if there's a bunch of |
Beta Was this translation helpful? Give feedback.
👍, with a caveat.
Caveat: Rust's primary units of encapsulation are a module and a crate, so generally it's perfectly fine to have stuff in module namespace. It is not a problem by itself. Often, the opposite is true -- people needlessly put stuff in impl blocks.
So, if there's a bunch of
FOO_XXX
constants and aFoo
type, it makes sense to writeFoo::XXX
instead. If, of the other hand, there's no single type to which a constant clearly belongs, it's better to leave it at the module level.