Skip to content

Commit

Permalink
changes
Browse files Browse the repository at this point in the history
  • Loading branch information
fyhhub authored Apr 7, 2024
1 parent f94380a commit b62a0ce
Showing 1 changed file with 82 additions and 0 deletions.
82 changes: 82 additions & 0 deletions src/rust-learn/6.常见Trait使用.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# 常见Trait使用


## FromStr
假设你有一个字符串"42",你想要将它解析为i32类型的数字:
```rust
let num_str = "42";
let num: i32 = num_str.parse().unwrap();
println!("Parsed number: {}", num);
```

对于**自定义类型**,如果你想能够使用`parse`方法将字符串转换为该类型的实例,你需要手动实现`FromStr trait`。下面是一个简单的例子,展示了如何为自定义类型实现`FromStr`

```rust
use std::str::FromStr;

struct Point {
x: i32,
y: i32,
}

impl FromStr for Point {
type Err = String;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts: Vec<&str> = s.split(',').collect();
if parts.len() != 2 {
return Err("Input must be in the format 'x,y'".to_string());
}
let x = parts[0].parse::<i32>().map_err(|_| "Invalid integer")?;
let y = parts[1].parse::<i32>().map_err(|_| "Invalid integer")?;
Ok(Point { x, y })
}
}

fn main() {
let point_str = "3,4";
let point: Point = point_str.parse().unwrap();
println!("Parsed point: ({}, {})", point.x, point.y);
}
```

## Add
为Point结构体实现Add\<Size\>特征,以便可以将Point和Size相加:

```rust
#[derive(Debug, PartialEq)]
struct Point {
x: i32,
y: i32,
}

#[derive(Debug, PartialEq)]
struct Size {
width: i32,
height: i32,
}

use std::ops::Add;

impl Add<Size> for Point {
type Output = Point;

fn add(self, other: Size) -> Point {
Point {
x: self.x + other.width,
y: self.y + other.height,
}
}
}

```

+ 需要注意的是,谁在前面,谁就要实现Add特征。

+ 如果是 Point + Point 就不需要给Add传泛型参数



## Send
+ 一个任务要实现 Send 特征,那它在 .await 调用的过程中所持有的全部数据都必须实现 Send 特征
+ 若实现了 Send 特征(可以在线程间安全地移动),那任务自然也就可以在线程间安全地移动。

0 comments on commit b62a0ce

Please sign in to comment.