Idiomatic name for `pub fn (&self) -> Option<T>`?

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::ok & Result:err, for example.

3 Likes

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).

2 Likes

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.

Rather than t1/t1_checked, I mostly see unwrap_t1/t1, e.g. Result::unwrap_err

2 Likes

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)?

1 Like

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 Vec or 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_t1, get_t2 and 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 t1/t2/t3.

1 Like

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.

opt_ and maybe_ prefixes seem strange. You won't see these in std (I don't think MaybeUninit and 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.

5 Likes

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