Rust 底层安全开发语言
简介:无GC内存安全底层语言,云原生、区块链、嵌入式、内核开发
小白入门案例1:HelloWorld
fn main() {
println!("Rust底层开发 | doc.yiliancai.com");
}
小白入门案例2:循环求和
fn main(){
let mut sum=0;
for i in 1..=100{sum+=i;}
println!("总和:{}",sum);
}
基础实操案例3:结构体用户模型
struct User{name:String,age:u32}
impl User{
fn new(name:&str,age:u32)->Self{Self{name:name.to_string(),age}}
}
基础实操案例4:Vec迭代器筛选
let users = vec![User::new("张三",22),User::new("李四",26)];
let adult:Vec<_> = users.iter().filter(|u|u.age>24).collect();
进阶项目案例5:文件读写
use std::fs;
fs::write("rust.txt","亿联财Rust案例")?;
let text = fs::read_to_string("rust.txt")?;
进阶项目案例6:reqwest异步网络请求
#[tokio::main]
async fn main()->Result<(),reqwest::Error>{
let res = reqwest::get("https://static.yiliancai.com").await?;
println!("{}",res.text().await?.len());
Ok(())
}
进阶项目案例7:多线程通道通信
use std::thread;
use std::sync::mpsc;
let (tx,rx) = mpsc::channel();
thread::spawn(move||tx.send(100).unwrap());
println!("{}",rx.recv().unwrap());
企业精通案例8:Arc+Mutex无锁并发计数
use std::sync::{Arc,Mutex};
let cnt = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10{
let c = Arc::clone(&cnt);
handles.push(thread::spawn(move||{*c.lock().unwrap()+=1;}));
}
企业精通案例9:FFI调用C动态库
extern "C"{fn c_add(a:i32,b:i32)->i32;}
fn main(){unsafe{println!("{}",c_add(10,20));}}
企业精通案例10:Tokio高性能TCP网关
use tokio::net::TcpListener;
#[tokio::main]
async fn main()->std::io::Result<()>{
let lis = TcpListener::bind("0.0.0.0:8080").await?;
loop{let (s,_)=lis.accept().await?;tokio::spawn(async move{});}
}