Home avatar

This is my blog

Rust 重借用

重借用

可知 Rust 的不能同时有两个以上, 那么如下情况会有矛盾:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
fn increase(cnt: &mut i32) {
    *cnt += 10;
}

fn main() {
    let mut cnt = 10;
    let cnt_ref = &mut cnt;

    // do something

    increase(cnt_ref);    // 同时有两个以上的可变引用?
    increase(cnt_ref);
    println!("{}", cnt_ref);
}

上面情况在实现应用中, 应该会出现。那么 Rust 给出了 “重借用 (reborrowing)” 的概念来允许这种情况:

Rust 常用组合器

组合器的作用

一般函数都是返回 Option 或 Result。但是每次都要判断它们是否是 None 或 Err, 再取出 Value 来操作会导致很烦琐, 有些情况下, 用组合器会比较方便。比如: 使用组合器可以链式编程。比如, 处理容器数据:

Rust 引用下的成员不能发生 Move

引用下的成员不能发生 move

For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
struct Foo {i: i32, string: String}

impl Foo {
    fn get_data(&self) -> i32 {
        return self.i;                  // 发生 Copy。
    }

    fn get_string(&self) -> String {
        return self.string;             // error. 引用的成员不能发生 Move。
    }

    fn move_string(self) -> String {    // 传拥有资源的标志符 self 才可以
        return self.string
    }
}
fn main() {
}

可见 Rust 比 C++ 在引用方面做了一些更加严格的限制。

使用 Ssh 连接到 Github

生成公私钥

1
ssh-keygen -t ed25519 -C "your_email@example.com" -f ~/.ssh/github

~/.ssh/config:

1
2
3
4
Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/github

将公钥上传到 github

  • 公钥: ~/.ssh/github.pub
  • 上传到 github: Settings -> SSH and GPG keys

测试是否成功

1
ssh -T git@github.com

ssh over https

如果使用机场访问 github, 可以会出现无法连接的情况, 因为有些机场会屏蔽 22 端口以防止网络攻击。改为 https 协议即可。

0%