Should I return & Option <Foo> or Option <& Foo> from the recipient?

I have a structure:

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

I want to create a getter for it, so the user cannot change 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 options?

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

+5
source share
2 answers

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

In addition, a general method for implementing a recipient is as follows:

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

Thus, you do not need to check the wrapped value in the receiver. If you want to return a mutable value, use as_mut() instead.

+8
source

If in doubt, choose the most flexible solution. This leaves you with more options for changing internal structures without changing its API.

In this case, this means selecting Option<&T> :

  • &Option<T> makes you refer to the option,
  • Option<&T> only reference to T is required.

So, for example, in the latter case, I could store Vec<T> or Result<T, Error> and still be able to pass Option<&T> . It is more flexible.

Note: this is why interfaces usually use &str instead of &String , &[T] instead of &Vec<T> , ... more flexibility!

+7
source

Source: https://habr.com/ru/post/1270059/


All Articles