Open In App

Rust – Result Type

Last Updated : 22 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In Rust, we have a result-type operator that is used for error-handling operations with the result-type operator. The Result type is wrapped in an enum that has two values – Ok and Err. Ok (T) denotes success while Err(E) is used for representing errors and error values (if present). 

While working with the Result type we encounter many methods including the parse() method which is Rust’s way of indicating failure when parsing a string operation fails. Whenever string parsing fails, the parse() method returns a Result type enum depending on the success or failure of the operation.

Syntax:

enum Result<T, E> {
  Ok(T),  //Ok => success
  Err(E),  //Err => error
}

Example 1:

Rust




#![allow(unused)]
fn main() {
#[derive(Debug)]
  
//VarOne and VarTwo are the versions passed in the GfgVersion
enum GfgVersion { VarOne, VarTwo}
  
fn parse_gfg_version_function(gfg_head_element: &[u8]) 
  -> Result<GfgVersion, &'static str> {
    match gfg_head_element.get(1) {
        None => Err("invalid HeadElement length"),
        Some(&20) => Ok(GfgVersion::VarOne),
        Some(_) => Err("invalid version"),
    }
}
  
let version_var = parse_gfg_version_function(&[10, 20, 30, 40, 50]);
match version_var {
    Ok(v) => println!("{v:?} is parsed"),
    Err(e) => println!(" {e:?} error is returned"),
}
}


Output:

 

Explanation:

In this example, we have declared an enum GfgVersion and have passed two variables VarOne and VarTwo that are actually the versions of the enum that are to be passed. A function parse_gfg_version is declared and a gfg_head_element having an unsigned internship of unsigned int is passed and the value is passed to the Result enum that holds the Gfgversion enum and a string. Now, we match the values present in the parsing vector. Here, at the position of the vector, we have 10 and we pass the index in the get function of the gfg_head_element.get(). As we can see that the index and the element match, therefore Rust gives us a success message stating Ok (v): VarOne is passed. Version_var is a variable that holds the parsing function values. This value is matched with the match function.

Another point to note is that if we pass any other value apart from the elements in the vector, we would get an error as per the Some(_) that we have declared in the match gfg_head_element().

Example 2:

Rust




#![allow(unused)]
fn main() {
#[derive(Debug)]
  
//x1 and x2 are the versions passed in the GfgVersion
enum GfgVersion { VarOne, VarTwo}
  
fn parse_gfg_version_function(gfg_head_element: &[u8])
  -> Result<GfgVersion, &'static str> {
    match gfg_head_element.get(1) {
        None => Err("invalid HeadElement length"),
       Some(_) => Err("invalid version"),
    }
}
  
let version_var = parse_gfg_version_function(&[10, 20, 30, 40, 50]);
match version_var {
    Ok(v) => println!("{v:?} is parsed"),
    Err(e) => println!(" {e:?} error is returned"),
}
}


Output:

 

Example 3: 

Rust




use std::num::ParseIntError;
  
fn main() -> Result<(), ParseIntError> {
    let number_to_str = "GeeksforGeeks";
    let num = match number_to_str.parse::<i32>() {
        Ok(num)  => num,
        Err(e) => return Err(e),
    };
    println!("{}", num);
    Ok(())
}


Output:

 

Explanation: 

Result type in Rust is helpful in such scenarios whenever we need to convert a numeric string to a number. In this example, we have imported the std::num::ParseIntError to check the number-to-string conversion. We have declared a variable number_to_string variable and assigned the string. Num matches whether the string is an int or a string and therefore it passes the error/success value accordingly. Here, we can clearly see that this is a pure string literal hence it returns a ParseIntError.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads