是否可以在不使用不安全或恐慌的情况下将潜在未初始化的变量标记为好? [英] Is it possible to mark a potentially uninitialized variable as good without using unsafe or panicking?

查看:41
本文介绍了是否可以在不使用不安全或恐慌的情况下将潜在未初始化的变量标记为好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以向编译器解释 v 变量在标记为 1 的行上是好的,而不使用 unsafe 或可能调用 panic! 的代码??

Is it possible to explain to the compiler that the v variable is good at the line marked as 1 without using unsafe or code that may call panic!?

#[derive(PartialEq, Debug)]
enum Enum {
    V1,
    V2,
    V3,
}

fn main() {
    let e = Enum::V1;

    let mut v: i32;

    if e == Enum::V1 || e == Enum::V2 {
        v = 17; //some complex, costy expression
    }
    match e {
        Enum::V1 | Enum::V2 => {
            println!("Results: {}", v); //1
        }
        _ => {}
    }
}

编译器报告:

error[E0381]: use of possibly uninitialized variable: `v`
  --> src/main.rs:18:37
   |
18 |             println!("Results: {}", v); //1
   |                                     ^ use of possibly uninitialized `v`

我有一个复杂的表达式来初始化v 在我的真实代码中而不是17v 的类型没有实现默认,我只需要 v 用于 Enum::V1Enum::V2 案例.

I have a complex expression to initialize v in my real code instead of 17, the type of v does not implement Default, and I only need v for the Enum::V1 and Enum::V2 cases.

在真正的代码中,我有 Enum::V1Enum::V2 的单独分支,我可以将 v 初始化移动到那里.

In the real code I have separate branches for Enum::V1 and Enum::V2, and I can move v initialization there.

我想让我的代码更清晰,我不想使用诸如 unsafeOption::unwrap

I want to make my code more clear and I don't want to use potentially bad things like unsafe or Option::unwrap

推荐答案

简单的方法就是初始化v;它是一个词,如果不需要,编译器可能会对其进行优化.在这种特殊情况下,您甚至可以将声明和初始化都移动到匹配的内部范围内,因为它不会在其他任何地方使用.

The simple method is to initialize v; it's a single word and the compiler can probably optimize it away if it is unnecessary. In this particular case, you could even move both the declaration and initialization into the inner scope of the match, because it isn't used anywhere else.

更简洁的做法是使无效的情况不可代表.这里 v 只在 V1V2 情况下才真正存在,所以如果我们加入这两者,我们就没有可能未初始化的名称价值.

The cleaner thing to do is to make the invalid case unrepresentable. Here v only really exists in the cases V1 or V2, so if we join the two we don't have a name for a possibly uninitialized value.

#[derive(PartialEq, Debug)]
enum Enum {
    V1 { v: i32 },
    V2 { v: i32 },
    V3
}

fn main() {
    let mut e = Enum::V1 { v: 17 };

    match e {
        Enum::V1 {v} | Enum::V2 {v} => {
            println!("Results: {}", v);//1
        }
        _ => {}
    }
}

这就是 Result 这样的类型Option 功能.

This is how types like Result and Option function.

这篇关于是否可以在不使用不安全或恐慌的情况下将潜在未初始化的变量标记为好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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