【rust】rust基础代码案例
文章目录
代码篇
HelloWorld
fn main() {
print!("Hello,Wolrd")
}
斐波那契数列
fn fib(n: u64) -> u64 {
let mut a = 0;
let mut b = 1;
for _ in 0..n {
let c = a + b;
a = b;
b = c;
}
a
}
fn main() {
let n = 10;
let result_list: Vec<String> = (1..n+1).map(|i| fib(i).to_string()).collect();
let result = result_list.join(",");
println!("{}", result);
}
计算表达式(加减乘除)
use std::io;
use std::num::ParseIntError;
fn parse_expression(expression: &str) -> Result<i32, ParseIntError> {
let mut result = 0;
let mut current_number = 0;
let mut operator = '+';
for token in expression.split_whitespace() {
match token {
"+" => operator = '+',
"-" => operator = '-',
"*" => operator = '*',
"/" => operator = '/',
_ => {
current_number = match token.parse::<i32>() {
Ok(num) => num,
Err(e) => return Err(e),
};
match operator {
'+' => result += current_number,
'-' => result -= current_number,
'*' => result *= current_number,
'/' => result /= current_number,
_ => {},
}
}
}
}
Ok(result)
}
fn main() {
println!("请输入表达式(例如:1 + 2 * 3):");
let mut input = String::new();
io::stdin().read_line(&mut input).expect("读取输入失败");
let expression = input.trim();
match parse_expression(expression) {
Ok(result) => println!("计算结果为:{}", result),
Err(e) => println!("解析表达式时出错:{}", e),
}
}
web接口
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};
#[get("/")]
async fn hello() -> impl Responder {
HttpResponse::Ok().body("Hello world!")
}
#[post("/echo")]
async fn echo(req_body: String) -> impl Responder {
HttpResponse::Ok().body(req_body)
}
async fn manual_hello() -> impl Responder {
HttpResponse::Ok().body("Hey there!")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(hello)
.service(echo)
.route("/hey", web::get().to(manual_hello))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
优化篇
target/目录占用一个g,仅仅一个actix的helloWorld demo
~/.cargo/config写入, 放到项目之外去,眼不见心不烦
[build]
target-dir = "/path/rust-target"
不过一个demo 接口, 你执行下cargo run 和 cargo build --release, 就占用1.2g。 这可真烧磁盘, 有node_module那味儿了。
升级rust版本, 通过rustup
export RUSTUP_DIST_SERVER="https://rsproxy.cn"
export RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup"
rustup update
cargo换源
~/.cargo/config写入
[source.crates-io]
registry = "https://github.com/rust-lang/crates.io-index"
replace-with = 'ustc'
[source.ustc]
registry = "https://mirrors.ustc.edu.cn/crates.io-index/"
windows下放弃吧,需要额外安装1g的toolchain并且要配合msvc(10g起步吧)或者mingw。
比linux下的工具链大多了
原文地址:https://blog.csdn.net/2301_76933862/article/details/143490108
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!