init code

This commit is contained in:
nap.liu
2023-12-08 19:41:26 +08:00
commit d1b95f1096
98 changed files with 2890 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "try_from_and_try_into"
version = "0.1.0"

View File

@@ -0,0 +1,8 @@
[package]
name = "try_from_and_try_into"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,38 @@
//!
//! TryFrom\TryInto 和 From\Into 非常相似,
//! 只不过 TryFrom\TryInto 会使用 Result 来包装可能失败的结果
//!
use std::convert::TryFrom;
use std::convert::TryInto;
#[derive(Debug, PartialEq)]
struct EvenNumber(i32);
impl TryFrom<i32> for EvenNumber {
// 指明错误的具体类型
type Error = ();
// 使用 Result 来包装结果成功还是失败
fn try_from(value: i32) -> Result<Self, Self::Error> {
if value % 2 == 0 {
Ok(EvenNumber(value))
} else {
Err(())
}
}
}
fn main() {
// TryFrom
assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8)));
assert_eq!(EvenNumber::try_from(5), Err(()));
// TryInto
let result: Result<EvenNumber, ()> = 8i32.try_into();
assert_eq!(result, Ok(EvenNumber(8)));
let result: Result<EvenNumber, ()> = 5i32.try_into();
assert_eq!(result, Err(()));
}