选项类型的类型转换 [英] Type casting for Option type
问题描述
我是Python的Rust的新手。我相信这是一个基本问题,但是我太新了,无法通过类型转换选项之类的关键字来找到答案。
在Python中,要让类型检查器知道返回类型不是 Optional [int] + int
,我们可以解决 assert
逻辑以强制类型检查器知道<$在行断言
之后,c $ c> x 永远不会无
。
来自键入import可选
def add_one(x:可选[int] =无)-> int:
如果x为空:
x = 0
断言x不为
返回x + 1
如果__name__ == '__main__':
add_one(0)#1
add_one()#1
add_one(999)#1000
在Rust中,假设接口相同,如何实现相同的目的?即,如何使编译器知道 x
的类型不再是 Option
了?
fn add_one(mut x:Option< i32>)-> i32 {
如果x ==无{
x = Some(0);
}
return x + 1;
}
fn main(){
add_one(Some(0));
add_one(无);
add_one(Some(999));
}
以下是错误消息:
错误[E0369]:二进制操作`+`不能应用于类型'std :: option :: Option< i32>`
$ p可能缺少std :: ops :: Add`的实现$ p>
-> tmp.rs:5:14
|
5 |返回x +1;
| -^-{整数}
| |
| std :: option :: Option< i32>
|
=注意:`std :: option :: Option< i32>`
请注意,我已经尝试过添加其他类型为i32的变量(
let y:i32 = x;
),但是它没有错误[E0308]:类型不匹配的
-> tmp.rs:5:22
|
5 |令y:i32 = x;
| ^预期为i32,发现枚举`std :: option :: Option`
|
=注意:预期类型为 i32
发现类型为 std :: option :: Option< i32>`
解决方案使用
unwrap_or
:fn add_one( x:选项< i32>)-> i32 {
x.unwrap_or(0)+ 1
}
fn main(){
assert_eq!(1,add_one(Some(0)));
assert_eq!(1,add_one(None));
assert_eq!(1000,add_one(Some(999)));
}
I'm newbie in Rust from Python. I believe it's a basic question, but I am too new to find the answer by keywords like Type Casting Option.
In Python, to make the type checker know return type is not
Optional[int] + int
, we can addressassert
logic to enforce the type checker knowx
will never beNone
after lineassert
.from typing import Optional def add_one(x: Optional[int] = None) -> int: if x is None: x = 0 assert x is not None return x + 1 if __name__ == '__main__': add_one(0) # 1 add_one() # 1 add_one(999) # 1000
In Rust, assuming the interface is same, how do achieve the same thing? Namely, how to make compiler know the type of
x
is notOption
anymore?fn add_one(mut x: Option<i32>) -> i32 { if x == None { x = Some(0); } return x + 1; } fn main() { add_one(Some(0)); add_one(None); add_one(Some(999)); }
Here's the error message:
error[E0369]: binary operation `+` cannot be applied to type `std::option::Option<i32>` --> tmp.rs:5:14 | 5 | return x + 1; | - ^ - {integer} | | | std::option::Option<i32> | = note: an implementation of `std::ops::Add` might be missing for `std::option::Option<i32>`
Note that I've tried things like adding another variable with type i32 (
let y: i32 = x;
), but it didn't work either with following message.error[E0308]: mismatched types --> tmp.rs:5:22 | 5 | let y: i32 = x; | ^ expected i32, found enum `std::option::Option` | = note: expected type `i32` found type `std::option::Option<i32>`
解决方案Use
unwrap_or
:fn add_one(x: Option<i32>) -> i32 { x.unwrap_or(0) + 1 } fn main() { assert_eq!(1, add_one(Some(0))); assert_eq!(1, add_one(None)); assert_eq!(1000, add_one(Some(999))); }
这篇关于选项类型的类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!