Skip to content

api: change Matrix::set to return Option<()> instead of bool #83

@acgetchell

Description

@acgetchell

Dependencies

Summary

Matrix::set returns bool for bounds-check success/failure. The idiomatic Rust pattern for fallible setters is Option<()> (or panicking like [] indexing). A bool return is easy to silently ignore, potentially masking out-of-bounds bugs.

Current State

pub const fn set(&mut self, r: usize, c: usize, value: f64) -> bool {
    if r < D && c < D {
        self.rows[r][c] = value;
        true
    } else {
        false
    }
}

Callers can write m.set(10, 0, 1.0); and silently do nothing. The #[must_use] attribute on the struct doesn't help here since the return is a primitive bool on a method, not the struct itself.

Proposed Changes

Change the return type to Option<()>:

pub const fn set(&mut self, r: usize, c: usize, value: f64) -> Option<()> {
    if r < D && c < D {
        self.rows[r][c] = value;
        Some(())
    } else {
        None
    }
}

This enables m.set(r, c, v)? in fallible contexts and triggers #[must_use] warnings from Option when the result is ignored (since Option itself is #[must_use]).

Alternatively, consider a panicking API matching standard indexing:

pub const fn set(&mut self, r: usize, c: usize, value: f64) {
    assert!(r < D && c < D, "index out of bounds");
    self.rows[r][c] = value;
}

This matches the behavior users expect from matrix[r][c] = value and is consistent with get returning Option (try-access) vs set being unconditional (assert-access).

Benefits

  • Idiomatic Rust API
  • Compiler warnings when the bounds-check result is ignored
  • Consistent with Option/Result conventions in the Rust ecosystem

Implementation Notes

  • This is a breaking change (return type change)
  • get returning Option<f64> is already idiomatic — this brings set in line
  • Existing callers using assert!(m.set(...)) would change to m.set(...).unwrap() or assert!(m.set(...).is_some())
  • Also gated on generic_const_exprs stabilization for the full v0.5.0 API revision

Metadata

Metadata

Assignees

No one assigned

    Labels

    apienhancementNew feature or requestrustPull requests that update rust code

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions