Rust基础用法

还是觉得只有列出参考资料的必要, 至于必须强调的细节才会主动列出

1. Cargo

参考资料: https://doc.rust-lang.org/cargo/index.html

如果需要添加一个依赖, 以clap为例:

1
cargo add clap --features derive

2. Rustup

参考资料: https://rust-lang.github.io/rustup/index.html

Crates

namedocdesc
claphttps://docs.rs/clap热门的CLI参数解析库

3. 常见用法:

3.1 raw string

raw string:

r#"..."# 使用r#…# 包裹的字符串内容不会被转义

1
2
3
4
5
6
7
8
9
let data = r#"
{
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
}"#;

3.2 socket

Socket编程: 注意, socket通信, 只有绑定了一个socket才能监听接受消息, 即: 只有socket是单向通信的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

use std::thread;
use std::os::unix::net::{UnixStream, UnixListener};
use std::println;
use std::io::prelude::*;
use std::time::Duration;
use std::io::{BufWriter, BufReader, Read};

fn handle_client(stream: UnixStream) {
let mut read_stream = BufReader::new(&stream);
let mut res = String::new();
// for line in read_stream.lines() {
// println!("Server: {}", line.unwrap());
// }
// read_lines is not recommended: as a new line ch is required.
read_stream.read_to_string(&mut res).unwrap();
println!("Server: {res:?}");

}

fn main() -> std::io::Result<()> {
let socket = std::path::Path::new("/tmp/dbs.socks");
if socket.exists() {
std::fs::remove_file(socket).unwrap();
}

// server
let t1 = thread::spawn(|| {
let listener = UnixListener::bind("/tmp/dbs.socks").unwrap();
for mut stream in listener.incoming() {
match stream {
Ok(stream ) => {
/* connection succeeded */
thread::spawn(|| handle_client(stream));
println!("bingo");
}
Err(err) => {
/* connection failed */
println!("{:?}", err);
break;
}
}
}

});

thread::sleep(Duration::from_millis(2000));

// client
let t2 =thread::spawn(|| {
// println!("{}", soc.)
for i in 1..10 {

// each request for one connection (Otherwise, the streaming is recognized as one transfer process)
let mut soc = UnixStream::connect("/tmp/dbs.socks").unwrap();
soc.write_all(b"Hello! dsa\n").unwrap();
// let mut reader = BufReader::new(&soc);
println!("send");
thread::sleep(Duration::from_millis(200));
}

});

t1.join().unwrap();
t2.join().unwrap();


Ok(())
}

3.3 错误处理

?可以用在Option后面, 也可以用在Result后面, 但在一个函数中, 如果返回值是Result, 则不能用在Option后, 否则有返回None的风险, 类型不一致, 但可以用ok_or来解决

1
2
3
4
5
6
use std::io::ErrorKind;

fn test() -> Result<(), std::io::Error> {
let res = do(A().ok_or(ErrorKin::AddrInUse)?)?;
res
}

通过ok_or, 将Option的矛盾上升到Error层面, 就好处理的得多了.


Rust基础用法
https://www.torch-fan.site/2022/07/21/Rust基础用法/
作者
Torch-Fan
发布于
2022年7月21日
更新于
2022年11月15日
许可协议