🦀

Ref Option T vs Option Ref T in Rust

Jul 5, 2024

Lecture on &Option<T> and Option<&T>

Introduction

  • Two Rust types: &Option<T> and Option<&T>
  • Argument: never use &Option<T>, always use Option<&T>
  • Explanation of why Option<&T> is preferred

Example Struct: Data

  • Large struct, doesn't implement Copy or Clone
  • Method: crunch -> returns an integer
  • Example Struct: Widget
    • Field: Option<Data>
    • Two accessor methods: data_a and data_b

Two Accessor Methods

  • data_a: returns a &Option<Data>
  • data_b: returns an Option<&Data>
  • Uses as_ref to convert between types

Analysis of Function Signatures

  • &Option<Data>: reference to the option, allows changes to option state
  • Option<&Data>: reference to data if it exists, no changes to option state
  • Mutability changes provide clearer differentiation
    • &mut Option<Data> vs Option<&mut Data>
    • Mutating option vs mutating data only

Advantages of Option<&T>

  1. Convenience: Call sites don't need to call as_ref themselves
  2. Encapsulation: Implementation details can change without API changes
  • Modifying internal storage without affecting API
    • Example: changing Option<Data> to Option<Box<Data>>
  1. Flexibility: Abstracting over various data sources

Practical Examples

  • Calling methods on struct Widget
    • data_a: must use as_ref for further operations
    • data_b: works directly, easier to use

Option Types in Parameters

  • &Option<T> vs Option<&T> for function params
    • Forces data to be in an Option when using &Option<T>
    • Flexibility with Option<&T>

Memory Layout

  • Option types and memory alignment
  • Niche optimization: Option<&T> uses null pointer optimization

Conclusion

  • Recommendation: avoid &Option<T> in APIs
  • Use Option<&T> for flexibility, encapsulation, and ease of use

Final Note

  • Invites valid use cases for &Option<T> in comments.