Which name to give to a builder function that returns an Option?

Hi,

I was wondering which name is better to use for a constructor that returns an Option.

Suppose a simple struct that represents a integer range (ignoring that already exists std::ops::Range) and suppose that you want to avoid reversed range:

struct Range {
    start: i32,
    end: i32,
}

impl Range {
    /// Create a range with provided values only 
    /// if start is not greater than end
    fn put_a_name_here(start: i32, end: i32) -> Option<Self> {
        if start <= end {
            Some(Range{ start, end })
        }
        else {
            None
        }
    }
}

I didn't find a clear suggestion for cases like this in the API guidelines.

Thank you.

How about between?

Don't get me wrong, maybe my original post was not clear (yeah, I read it again and it can be misunderstood). My question actually was if there is a special guidelines for naming constructors that returns Option.

So as I can see (since @RustyYato is proposing to delete the post) there is not any guideline and I can use a name that makes sense (for example in this case @fosskers suggestion could work).

As far as I can tell, there is no conventional prefix or suffix for methods that return Option, for example the Iterator trait has a mix of different return types, but the names are all succinct:

Iā€™d carry that through to associated functions and constructors too, new is probably fine unless there is something more specific to use. Maybe a Result<Self, OrderError> would be better than an Option though.

I'm not proposing to delete the post, I deleted my answer because I misunderstood your question and didn't have time to correct my mistake

FWIW, std seems fine with a new that returns Option: NonZeroU32 in std::num - Rust

2 Likes

I second new(). In constructors, fallibility is fine and expected (and often it's the idiomatic choice, as in your case).

2 Likes

My code has several new() that return Result.

1 Like

Thank you! I was looking for an std example.

Ups... My fault, I misunderstood the automatic message. :relaxed:

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.