[WIP] Rust 学习📓
- Dominant language
- No language data
- Stars
- 7
- Forks
- 0
- PR merge metrics
- No merged PRs in 30d
Description
### 解引用强制多态会自动的将指针或智能指针的引用转换为指针内容的引用。
```rust
use std::ops::Deref;
struct A(i32);
impl Deref for A {
type Target = i32;
fn deref(&self) -> &i32 {
&self.0
}
}
fn add_one(v: &i32) -> i32 {
v + 1
}
fn main() {
let a = A(1);
// impl Deref for A {type Target = B;}
// &A == &B
assert_eq!(add_one(&a), 2);
}
```
解引用时 rust 会偷偷地调用 deref 方法:
```rust
*a == *(a.deref())
```
强制解引用多态是针对**函数参数**的,是 rust 为了方便传递**引用类型的参数**而提供的语法糖,为了把不匹配的引用类型转换成与函数签名中的参数相同的类型而做的语法糖:
```rust
fn hello(name: &str) {
println!("hello {}", name);
}
// hello(&a) == hello(a.deref())
```
### scan 和 fold 的区别:
scan 是个适配器(返回 Iterator),fold 是个消费器(返回实现了 FromIter 的类型)。scan closure 的第一个参数是个可变引用 &mut,每次迭代需要改变第一个参数,且 closure 的返回值需要是个 Optional
```rust
fn main() {
let a = [1,2,3,4];
a.iter().scan(0, |a, c| {
println!("scan: {} {}", a, c);
*a = *a + c;
Some(*a)
}).collect::>();
a.iter().fold(0, |a, c| {
println!("fold: {} {}", a, c);
a + c
});
}
```
输出:
```shell
scan: 0 1
scan: 1 2
scan: 3 3
scan: 6 4
fold: 0 1
fold: 1 2
fold: 3 3
fold: 6 4
```
### slice a &str
```rust
let s = "abcdefghi" // &str;
s[1..3]; // str
&s[1..3]; // &str
s[1..3].to_string(); // String
let s = String::from("abcdef"); // String
s[1..3]; // str
```
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.