函数是否可以根据函数中的条件语句返回不同类型? [英] Can a function return different types depending on conditional statements in the function?

查看:47
本文介绍了函数是否可以根据函数中的条件语句返回不同类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以根据函数中的条件返回不同的类型:如果您删除'||,此代码将起作用bool' 和 'if/else' 语句.

I was wondering if it was possible to return different types depending on the conditions in the function: This code will work if you remove '|| bool' and the 'if/else' statements.

提前致谢.

fn main() {
    let vector: Vec<i32> = vec![0, 2, 5, 8, 9];
    let targetL i32 = 3;
    let found_item = linear_search(vector, target);
    println!("{}", &found_item);
}
fn linear_search(vector: Vec<i32>, target: i32) -> i32 || bool {
    let mut found: i32 = 0;
    for item in vector {
        if item == target {
            found = item;
            break
        }
    }
    if found == 0 {
        false
    } else {
        found
    }
}

推荐答案

在编译时必须知道精确的类型(并且随后被擦除).您不能随意决定在运行时返回哪些类型.

The precise type must be known at compile time (and is subsequently erased). You cannot decide arbitrarily which types to return at runtime.

但是,您可以通过将类型包装到通用枚举中(替换代码中的 ||)来实现您尝试过的操作:

However, you can do you've tried to do, by wrapping the types into a generic enum (which replaces the || in your code):

enum TypeOr<S, T> {
    Left(S),
    Right(T),
}

fn linear_search(vector: ...) -> TypeOr<i32, bool> { //...

缺点是您必须先从枚举中解开值,然后才能对结果执行任何其他操作.然而,这在实践中并不是那么困难.

The downside is that you must unwrap the value from the enum before you can do anything else with the result. However, this isn't so arduous in practice.

这本质上是常用的OptionResult 类型的通用版本.

This is essentially a generalised version of the commonly used Option and Result types.

实际上,在您的情况下,Option 类型的语义很好地为您服务:您永远不会返回 true,因此您可以将 None 结果与 false 结果你的函数返回,这捕捉了你试图表达的想法:要么你的线性搜索找到目标并返回它(Some(found)),或者不返回,并且没有返回值 (None).

In fact, in your case, you are served very nicely by the semantics of the Option type: you never return true, so you may equate the None result with the false result your function returns, and this captures the idea you're trying to express: either your linear search finds the target and returns it (Some(found)), or it does not, and has nothing to return (None).

这篇关于函数是否可以根据函数中的条件语句返回不同类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆