Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I return &Option<Foo> or Option<&Foo> from a getter?

Tags:

rust

I have a struct:

struct Foo {}
struct Boo {
    foo: Option<Foo>,
}

I want to create getter for it, so user cannot modify it but can read it:

impl Boo {
    pub fn get_foo(&self) -> ? { unimplemented!(); }
}

Should I return &Option<Foo> or Option<&Foo>? Are there any advantages between these two variants?

I use both variants in my program, and it became an inconvenience to mix them, so I want to choose one of them for the entire program.

like image 419
user1244932 Avatar asked Jul 21 '17 12:07

user1244932


People also ask

What's a good excuse to return something?

The most common causes of purchase returns are unmet expectations, damaged or defective products, and incorrect fit. Any of these issues can be caused by failures on the merchant's part or by events the merchant had no control over.

What is return abuse?

Refund abuse (aka. returns abuse) occurs when a customer uses the returns policy of a merchant so much that it becomes unprofitable. Customers may also abuse refunds by faking returns/receipts, or reselling merchandise.

How do you decide if I should go back to work?

Think about whether the work will satisfy you or if you will crave something new. Simply, would you prefer to return to your previous role, do you want something new, or are you in need of a career relaunch?

Why is return important?

2) Let the customer return it however they want This does two things: it enables the customer to get an item exchanged or their money back quicker so keeping them happy; and it allows the retailer or wholesaler to make those returned goods available for sale quicker.


1 Answers

Use Option<&T> instead of &Option<T>. Callers are interested in the wrapped value, not in Option.

Also, the common way to implement a getter like this is as follows:

impl Boo {
    pub fn get_foo(&self) -> Option<&Foo> { self.foo.as_ref() }
}

This way you don't need to check the wrapped value in the getter. If you want to return a mutable value, use as_mut() instead.

like image 123
Tibor Benke Avatar answered Sep 21 '22 07:09

Tibor Benke