I have an Enum, and thus a number of functions of type signature:
pub fn (&self) -> Option<T1>
pub fn (&self) -> Option<T2>
pub fn (&self) -> Option<T3>
is there an idiomatic name for this? I'm considering:
get_t1, get_t2, get_t3,
opt_t1, opt_t2, opt_t3,
maybe_t1, maybe_t2, maybe_t3
Just the variant name, it seems:
Result:err, for example.
I think it is usual to use variant names, regardless of their return types, unless you want to provide multiple versions for different return type.
When I want to implement both
-> T1 and
-> Option<T1>, then I'll name them
fn t1(&self) -> T1 and
fn t1_checked(&self) -> Option<T1> or something like that (with
i32::abs(self) -> i32 and
i32::checked_abs(self) -> Option<i32> in mind).
Because of auto complete reasons in IntelliJ, I think I actually want a English word, so it limits the potential auto completion options.
I guess I'll go with
get_ for now.
t1_checked, I mostly see
I guess it's worth asking why not just
impl From<Foo> for Option<T1>, etc or is that not possible in your case (due to crate restrictions)?
I think it is the best option if you aren't willing to go with
t1. But if your goal is to have an English word, what about remaking your types into english words?
"get" has the connotation of retrieving something from inside - like getting a value from a
HashMap. The reason I'd leave this out for enum methods is that you aren't getting an inner value - you're unwrapping the enum. The operation is one of transforming the enum from one form (any of X, Y, Z) into another (maybe X) - you're getting all of it, not some subset.
If that isn't true for your enum methods - if you could have
get_t3 all return Some for the same enum, then
get is appropriate. But if they are exclusive, I'd argue that the right name really is
Rust API guidelines say:
With a few exceptions, the
get_ prefix is not used for getters in Rust code.
Such methods are usually called
as_.... For example, see serde_json::Value. Note that if the type is not
Copy, these methods return a reference.
maybe_ prefixes seem strange. You won't see these in std (I don't think
option_env! count). The only widely used prefix for fallible operations is
try_. In many cases you don't need to indicate this with a prefix at all. The return type (
Option<T>) already makes it clear that the value may be absent, and the type system won't let the user miss it, so the prefix doesn't communicate anything new. And usually you don't need to have a counterpart method that returns
T (or it has another name, like
x_or_default), so you don't need a prefix to resolve a name collision either.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.