Pattern matching
In Rust, the match keyword is used to compare a value against a set of patterns and execute code based on which pattern matches. This is especially useful with enums like Option
.
#![allow(unused)] fn main() { let maybe_number: Option<i32> = Some(42); match maybe_number { Some(n) => println!("The number is: {}", n), None => println!("No number available."), } }
This pattern ensures we safely handle both the presence and absence of a value.
Predict function
We use the exact same technique in our model to check whether it has been fitted. Since beta is of type Option<f64>
, we can match on its value to determine whether a prediction can be made:
#![allow(unused)] fn main() { match self.beta { Some(beta) => Ok(x * beta), None => Err("Model not fitted".to_string()), } }
The full function takes this form:
#![allow(unused)] fn main() { impl RidgeEstimator { /// Predicts target values given input features. /// /// # Arguments /// - `x`: Input features as a 1D array. /// /// # Returns /// A `Result` containing the predicted values, or an error if the model /// has not been fitted. pub fn predict(&self, x: &Array1<f64>) -> Result<Array1<f64>, String> { match &self.beta { Some(beta) => Ok(*beta * x), None => Err("Model not fitted".to_string()), } } } }
Here, we also decide to explicitly raise an error if the model has not been fitted. To do this in a type-safe way, we use Rust’s Result
enum, which is commonly used for functions that may fail. The Result
enum can be either Ok(value)
(indicating success) or Err(error)
(indicating failure). More details about error handling are given in the next section.