跳到主要内容

rust开发常用demo收集

多次不可变引用处理

trait Delegate {
fn send_data(&mut self, b: &str, a: &mut String);
}

struct A<'a> {
index: i32,
content: String,
delegate: Box<&'a mut dyn Delegate>,
}

impl A<'_> {
fn new<'a>(d: &'a mut dyn Delegate) -> A {
A { index: 0, content: "hello word".to_string(), delegate: Box::new(d) }
}

// 开始
fn start(&mut self) {
//littley注:将变量值单独取出来可以解决多次不可变引用 问题


//self.delegate.send_data("Hello,world!", self);
//error[E0499]: cannot borrow `*self` as mutable more than once at a time
let mut a = &mut self.delegate;
let mut b = &mut self.content;
a.send_data("hello", b);
}

//接收数据
fn receive(&mut self, data: &str) {
self.content = data.to_string();
}
}

//代理结构体,里面实现具体逻辑
struct MockD {
index: i32,
}

impl MockD {
fn new() -> MockD {
MockD { index: 0 }
}
}

impl Delegate for MockD {
fn send_data(&mut self, b: &str, a: &mut String) {
println!("已发送数据:{}", b);
// 步骤序号 + 1, 并发送出去, 此处根据具体的业务需求变化
self.index += 1;
*a = self.index.to_string();
// a.receive(&self.index.to_string());
}

}

fn main() {
let mut d = MockD::new();

let mut a = A::new(&mut d);

a.start();

}

match if let 元组

#[test]
fn test_for_match_tuple1() {
let s1 = 2;
let s2 = 1;
match (s1, s2) {
(1, 1) => println!("1"),
(1, 2) => println!("2"),
(2, 1) => println!("3"),
_ => println!("df"),
}
}

match 元组是存在多个组合,必要时应考虑所有组合情况


#[test]
fn test_for_match_tuple() {
let s1 = Some(1);
let s2 = Some(2);
if let (Some(t), Some(t1)) = (s1, s2) {
println!("{}", t);
println!("{}", t1);
}
}

注意这里的也只是匹配了特定的情况

create依赖冲突解决

当第三方库依赖时冲突时,如reqwest 依赖了openssl但是也有其他库使用了不同版本的的openssl 统一指定如下

[patch.crates-io]
uuid = { path = "../path/to/uuid" }

uuid = { path = "git_path/to/uuid" }