How do I return a Result data type in Rust?

1.8k Views Asked by At

I have the code below

fn main() {
    let num: i64 = 600851475143;

    println!("Largest prime: {}", largest_prime_factor(num));


}

fn largest_prime_factor(num:i64) -> Result<i64, Error<None>> {
    let mut primes: Vec<i64> = Vec::new();

    for x in 1i64..=num {
     if num % x == 0 {
         if (x == 2) | (x==3) | ((x-1) % 6 ==0) | ((x+1) %6 ==0) {
             primes.push(x);
         }
     }
    }
    let max_value = primes.iter().max()?;

}

The largest_prime_factor function's role is to find the largest prime factor of the number in it's input.

I push all prime factors to the primes vector, and then return the largest, but I'm unsure how to return the largest integer. If the .max() function returns an error - the documents say it would return None, but when I place None as a possibility to return, it says it isn't a data type, and to use my variant's enum, but look at the docs, the None does seem to be the enum. So what does the function actually return? Am I using ? incorrectly

1

There are 1 best solutions below

2
On BEST ANSWER

If you look at the signature for the max method, you can see that it returns an Option:

fn max(self) -> Option<Self::Item>

In this case, it returns Option<i64>.

The Option type is an enum which has two variants, to simplify:

enum Option<T> {
    Some(T),
    None,
}

Here, None isn't a type, but an enum variant.

Here is what your method should look like:

fn largest_prime_factor(num:i64) -> Option<i64> {
    let mut primes: Vec<i64> = Vec::new();

    for x in 1i64..=num {
     if num % x == 0 {
         if (x == 2) | (x==3) | ((x-1) % 6 ==0) | ((x+1) %6 ==0) {
             primes.push(x);
         }
     }
    }
    
    primes.iter().max().cloned()
}

You don't even need a Result type here, as it doesn't really make sense to return an error.

Returning an Option signals that there can be zero or one result.