Option only as return value?


#1

Hello,

style question. In Java 8 Optional is recommended to be used a return value only:

http://blog.jhades.org/java-8-how-to-use-optional/

In Rust I also use Option as a return value. But there are also cod examples in some projects (e.g. using the new “constructor”) that use Option as an optional parameter.

In Scala Option is also sometimes used as a parameter.

I’ve had this discussion with several Java and Scala developers and often people have strong preferences.

Are there any recommend best practices for Rust? Should Option be restricted to return values?

Just curious,

Markus


#2

There’s no similar suggestion in Rust. Since Java already has null, it
has different goals with Optional. From the link:

Optional is not meant to be a mechanism to avoid all types of null
pointers. The mandatory input parameters of methods and constructors still
have to be tested for example.

and from a link of the link:

Optional is being added for the value it offers in “fluent” sequences of
statements. In this context use of Optional as a visible type or for
serialization isn’t relevant

In Rust, Option<T> is the mechanism to avoid all types of null
pointers, and wasn’t added solely for sequencing.


#3

Thanks Steve. That what I also got from the Rust docs (thanks for writing so much of it!).

Just wanted to be sure as this is sometimes a very fiercely debated subject in the Java world and some Java programmers might assume the same logic for Rust.

I really like that Rust avoids null.


#4

As both Rustacean and Java programmer, I’d like to add that in Java, Optional is often avoided in fields and elsewhere because it adds another layer of indirection: Let’s say you have an Object of type Foo with an Optional<String> name field. Since Java does not have value types yet, this will be a reference to our Foo, which contains a reference to our Optional<String> which may or may not contain a reference to a String.

On the other hand, in Rust, the type is flat, so the only extra cost we pay – sometimes – is for the Option variant tag. There is no indirection at all. Also References, which by definition cannot be null, implement the NonZero trait and are thus subject to an optimization for Option that avoids the variant tag – as are all other objects that implement NonZero.


#5

I personally would avoid using Option for optional arguments simply because it is both verbose and unclear. In the call

function (x, y, None, None);

How do you know what the None means? For a similar reason I try to avoid bool as an argument. In both cases a custom enum is often more clear. Or one could use a builder style approach with chained method calls to add the optional parameters, when there is no particular meaning applied to omitting the parameter.