[英]How do I return a Result data type in Rust?
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. largest_prime_factor
函数的作用是找到其输入中数字的最大素因子。
I push all prime factors to the primes
vector, and then return the largest, but I'm unsure how to return the largest integer.我将所有素数因子推到
primes
向量,然后返回最大的,但我不确定如何返回最大的 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.如果 the.max() function 返回错误 - 文档说它会返回 None,但是当我将 None 作为返回的可能性时,它说它不是数据类型,并使用我的变体枚举,但看看在文档中, None 似乎确实是枚举。 So what does the function actually return?
那么 function 究竟返回了什么? Am I using
?
我在用
?
incorrectly错误地
If you look at the signature for the max
method, you can see that it returns an Option:如果您查看
max
方法的签名,您可以看到它返回一个选项:
fn max(self) -> Option<Self::Item>
In this case, it returns Option<i64>
.在这种情况下,它返回
Option<i64>
。
The Option type is an enum which has two variants, to simplify: Option 类型是一个枚举,它有两个变体,为了简化:
enum Option<T> {
Some(T),
None,
}
Here, None
isn't a type, but an enum variant.在这里,
None
不是类型,而是枚举变体。
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.这里甚至不需要 Result 类型,因为返回错误没有任何意义。
Returning an Option signals that there can be zero or one result.返回一个 Option 表示可以有零个或一个结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.