![](https://img-blog.csdnimg.cn/20201014180756930.png?x-oss-process=image/resize,m_fixed,h_64,w_64)
rust
search_star
个人博客seekstar.github.io
展开
-
rust交换数组中的两个元素
不可以直接用std::mem::swap,因为这个函数需要拿两个可变引用,但是不可以同时拿两个这个数组的可变引用。所以要么手写:let tmp = a[i];a[i] = a[j];a[j] = tmp;要么用Vec::swap:a.swap(i, j);其内部实现:fn swap(&mut self, a: usize, b: usize) { unsafe { // Can't take two mutable loans from one vecto翻译 2021-10-20 21:52:18 · 1049 阅读 · 0 评论 -
rust交换两个引用
fn main() { let x = 1; let y = 2; let mut xx = &x; let mut yy = &y; println!("{} {}", xx, yy); let tmp = xx; xx = yy; yy = tmp; println!("{} {}", xx, yy);}1 22 1这样是可以的。但是如果是在函数里交换传进来的两个引用:fn foo(x: &i3原创 2021-10-19 18:53:46 · 374 阅读 · 0 评论 -
rust格式控制
https://doc.rust-lang.org/std/fmt/原创 2021-10-12 20:59:05 · 160 阅读 · 0 评论 -
rust翻转数组
https://doc.rust-lang.org/stable/std/primitive.slice.html#method.reverse原创 2021-10-06 18:23:49 · 843 阅读 · 0 评论 -
rust二分搜索
如果要二分搜索某个特定值,可以用binary_search:https://doc.rust-lang.org/stable/std/primitive.slice.html#method.binary_search如果要实现C++里的lower_bound和upper_bound类似的功能,可以用partition_point:https://doc.rust-lang.org/stable/std/primitive.slice.html#method.partition_pointpub fn原创 2021-10-06 17:38:25 · 350 阅读 · 0 评论 -
rust打印变量类型
可以试试std::any::type_name。注意,这个是unstable的。use std::collections::HashSet;fn print_type_of<T>(_: &T) { println!("{}", std::any::type_name::<T>())}fn main() { let mut s = HashSet::new(); let ve = vec![1, 2, 1, 3, 2, 4]; pri翻译 2021-09-29 20:30:45 · 1791 阅读 · 0 评论 -
rust踩坑笔记
mpsc需求:需要在一个线程里读取数据,发送给另一个线程处理。我的方法:用mpsc的channel发送和接收。坑:mpsc的channel从不阻塞发送方,它有无限的缓冲。结果读取远远比写入快,导致大量内存被消耗。解决方案:用sync_channel:pub fn sync_channel<T>(bound: usize) -> (SyncSender<T>, Receiver<T>)这个bound参数应该指的是个数。文档:https://doc.ru原创 2021-09-29 15:54:29 · 326 阅读 · 0 评论 -
rust 堆上二维数组
用ndarray:https://docs.rs/ndarray/0.15.3/ndarray/Rust 多维数组 ndarray例子:use ndarray::Array2;fn main() { let mut a = Array2::<usize>::zeros((2, 3)); println!("{:?}", a.dim()); for i in 0..2 { for j in 0..3 { a[[i, j]]原创 2021-09-15 16:56:00 · 343 阅读 · 0 评论 -
tokio JoinHandle abort不起作用
可能是因为这个线程在一个没有await的死循环里?参考:https://users.rust-lang.org/t/abort-asynchronous-task/61961原创 2021-08-25 17:36:59 · 279 阅读 · 0 评论 -
rust运行shell命令并获取输出
rust:执行shell命令原创 2021-08-17 17:53:28 · 3698 阅读 · 0 评论 -
rust 定时执行
tokio = { "version" = "1.10", features = ["full"] }use tokio::time;async fn print() { let mut interval = time::interval(time::Duration::from_secs(1)); loop { interval.tick().await; println!("2333"); }}#[tokio::main]async原创 2021-08-16 16:20:40 · 3035 阅读 · 0 评论 -
ubuntu cargo flamegraph
cargo flamegraph运行指定binnary:cargo flamegraph -b your-binnary常见错误的处理could not spawn perfsudo apt install linux-tools-commonWARNING: perf not found for kernel 4.15.0-144 You may need to install the following packages for this specific kernel:原创 2021-08-12 13:43:30 · 432 阅读 · 0 评论 -
rust scoped thread pool
用rayon即可。use rayon;fn fun(a: &mut i32) -> i32 { *a += 1; return *a + 233;}fn main() { let mut a = 233; let pool = rayon::ThreadPoolBuilder::new().num_threads(8).build().unwrap(); let ret = pool.install(|| fun(&mut a));原创 2021-08-09 16:53:11 · 336 阅读 · 0 评论 -
rust private super trait
pub(crate) mod private { #[doc(hidden)] pub trait FooPrivate<Arg> { fn foo(&self, arg: Arg); }}pub trait Foo<Arg>: private::FooPrivate<Arg> { /* other public methods */}原文:https://jack.wrenn.fyi/blog/翻译 2021-08-03 16:13:31 · 128 阅读 · 0 评论 -
rust存取一个含有borrowed域的结构体
直接存取不可以:use std::fs::File;use std::io::{BufWriter, BufReader};use serde::{Serialize, Deserialize};extern crate bincode;#[derive(Debug, Serialize, Deserialize)]struct A<'a> { a: &'a [u8]}fn main() { let a: &[u8] = &[2,原创 2021-07-28 10:31:32 · 239 阅读 · 0 评论 -
rust serde deserialize borrowed member
对于borrowed成员,deserializer可以借用输入里的对应部分。serde_json序列化时会将所有部分转换成字符串,这样除非这个成员是字符串,否则deserializer就不能借用到了,会报错:invalid type: sequence, expected a borrowed byte arraybincode序列化时会将各部分保存为二进制码,比如&'a [u8]成员被序列化之后仍然是一个u8字符串,因此对于大部分情况都能直接借用。use serde::{Serialize原创 2021-07-27 17:04:01 · 364 阅读 · 0 评论 -
vscode rust插件find all references无结果
好像是因为这个插件没有人维护了,自从2020年5月就没有再更新了:https://marketplace.visualstudio.com/items?itemName=rust-lang.rust&ssr=false#version-history不过这个插件的一个开发者matklad搞了另一个插件:rust-analyzer:https://github.com/rust-lang/vscode-rust/issues/812功能跟rust插件差不多,也有find all referen原创 2021-07-27 12:02:10 · 330 阅读 · 0 评论 -
rust note: `#[warn(dead_code)]` on by default
如果要允许未使用的代码,在前面加上#[allow(dead_code)]即可。参考文献:https://doc.rust-lang.org/rust-by-example/attribute/unused.html转载 2021-07-19 19:13:26 · 2045 阅读 · 0 评论 -
rust忽略Result
fn main() { let _ = std::fs::remove_dir_all("tmp");}原文:https://stackoverflow.com/questions/51141672/how-do-i-ignore-an-error-returned-from-a-rust-function-and-proceed-regardless翻译 2021-07-15 16:42:39 · 225 阅读 · 0 评论 -
rust fragment specifier
SpecifierDescriptionExamplesidentIdentifierx, foopathQualified namestd::collection::HashSet, Vec::newtyTypei32, &T, Vec<(char, String)>exprExpression2+2, f(42), if true { 1 } else { 2 }patPattern_, c @ ‘a’ … ‘z’, ...转载 2021-07-14 13:24:21 · 77 阅读 · 0 评论 -
rust const generic
struct ModVal<const P: usize> { v: usize}impl<const P: usize> ModVal<P> { // std::assert!(P + P <= usize::Max()); fn new(v: usize) -> Self { Self { v } }}impl<const P: usize> std::ops::AddAssign<原创 2021-07-14 12:44:56 · 162 阅读 · 0 评论 -
rust进度条
用indicatif即可。官方文档:https://docs.rs/indicatif/0.16.2/indicatif/一个简单的例子:use indicatif::ProgressBar;fn main() { let bar = ProgressBar::new(1000); for _ in 0..1000 { bar.inc(1); std::thread::sleep(std::time::Duration::from_millis(2)翻译 2021-07-07 16:45:40 · 404 阅读 · 0 评论 -
rust多行字符串字面量
let string = "line one line two";相当于line one\n line two,注意第二行的前导空格还在。let string = "one line \ written over \ several";相当于one line written over several,注意前导空格被忽略了。let string = "multiple\n\ lines\n\ with\n\翻译 2021-07-06 15:56:07 · 1688 阅读 · 0 评论 -
rust格式化打印到文件
用write!和writeln!即可。write!(&mut writer, "Factorial of {} = {}", num, factorial);writeln!就是在最后自动加一个换行。原文:https://stackoverflow.com/questions/32472495/how-do-i-write-a-formatted-string-to-a-file翻译 2021-07-05 09:58:41 · 284 阅读 · 0 评论 -
cargo build找不到openssl库
ubuntu的话安装libssl-devsudo apt install libssl-dev如果还是找不到,其实报错信息里有提示安装pkg-config可能可以解决问题:sudo apt install pkg-config然后再跑cargo build就可以了。原创 2021-07-01 16:15:14 · 469 阅读 · 0 评论 -
cargo build指定目标
cargo build --bin <name>原创 2021-07-01 14:15:20 · 1029 阅读 · 0 评论 -
rust scoped thread
rust里,std::thread::spawn要求传入的闭包的生命周期必须是'static的,也就是说闭包中不能借用局部变量,因为rust不知道这个局部变量会不会突然就被释放了。但是一般情况下,spawn之后会调用join来确保函数返回前子线程会终止,也就是说实际上可以保证子线程在跑的时候,这个局部变量一直是有效的。这种情况下怎么办呢?这就需要用到第三方crate:crossbeam。其中引入了scoped thread的概念,即通过强制join来确保子线程的生命周期局限在一个范围里,那么只要局部变量的原创 2021-05-19 19:00:03 · 641 阅读 · 0 评论 -
rust unresolved import `minigrep`
rust The book练习题minigrep:https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.htmlcargo run报错:unresolved import `minigrep。原因是把lib.rs命名成run.rs了。改回lib.rs就好了。这说明lib.rs的名字是有特殊含义的。...原创 2021-05-14 16:32:56 · 529 阅读 · 0 评论 -
rust泛型初始化成0
std::num::Int被deprecated了。所以只能用别人的crate或者自己实现Zero了。github上有一个不错的:https://github.com/rust-num/num-traitspub trait Zero: Sized + std::ops::Add<Self, Output = Self> { fn zero() -> Self; fn is_zero(&self) -> bool;}macro_rules! zero原创 2020-09-04 00:02:25 · 582 阅读 · 0 评论 -
rust从一行中读取数组
use std::io;fn main() { let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); let ns: Vec<i32> = input.trim().split(' ').map(|x| x.parse().unwrap()).collect(); for v in ns { print!("{} ", v); }}原创 2020-08-26 13:50:41 · 684 阅读 · 0 评论 -
算法竞赛中rust的一种比较健壮的读入
以PAT 甲级1003为例关键部位fn main() { loop { let mut input = String::new(); if 0 == io::stdin().read_line(&mut input).unwrap() { break; } let input = input.trim(); if input.len() == 0 { conti原创 2020-08-25 23:53:13 · 362 阅读 · 0 评论 -
rust print固定宽度左边补零
fn main() { println!("{:0>3}", 2333); println!("{:0>3}", 233); println!("{:0>3}", 23); println!("{:0>3}", 2); println!("{:0>3}", 0); println!("{:0>3}", -2);}其中>表示向右对齐,0是在左边补的字符。23332330230020000-2...原创 2020-08-25 19:34:43 · 1173 阅读 · 0 评论 -
rustc 编译release
rustc % -C opt-level=3 -C debuginfo=0原创 2020-08-19 10:37:15 · 1071 阅读 · 0 评论 -
rust识别EOF
参考:https://stackoverflow.com/questions/41210691/how-to-check-for-eof-in-read-line-in-rust-1-12如果read_line返回的是Ok(0)那么就是EOF了。跟空行的区别在于空行实际上还有一个换行符,所以是Ok(1)。 let mut input = String::new(); loop { if 0 == io::stdin().read_line(&原创 2020-08-17 16:45:54 · 642 阅读 · 0 评论 -
rust查看标准库源码
点击API文档的src即可看到。原创 2020-08-17 10:19:18 · 1267 阅读 · 1 评论 -
rust单行读取多个整数
rust读取真的很麻烦。网上的方法一般是用split(’ ')来分割出整数。但是如果中间有多个空格就凉了。后面查阅官方文档发现了split_whitespace,可以用多个空白字符(空格和tab,不含换行符)分割。use std::io;fn main() { let mut input=String::new(); io::stdin().read_line(&mut input).unwrap(); let mut s = input.split_whitespac原创 2020-08-15 10:49:13 · 1353 阅读 · 1 评论 -
rust学习笔记
安装rust之后rustup doc文档就会在浏览器里打开。点击里面的The Rust Programming Language,就可以看到入门书的网页版了。cargo文档cargo doc --open可以生成并在浏览器打开项目的文档。新建项目cargo new <项目名>语法_是通配符这里指匹配所有的Err,不管里面是啥。常见函数字符串成员函数trim去掉前后空格。parse把字符串转成特定类型(通过要被赋值给的变量确定?)...原创 2020-08-15 10:41:03 · 231 阅读 · 1 评论 -
linux 非交互式安装rust
官网提供的安装方式是交互式的,需要手动输入回车来使用默认配置。curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh其实下载下来的脚本里有使用帮助rustup-init 1.22.1 (76644d669 2020-07-08)The installer for rustupUSAGE: rustup-init [FLAGS] [OPTIONS]FLAGS: -v, --verbose原创 2020-08-05 17:14:56 · 398 阅读 · 0 评论