为什么Rust有String和str?String和之间有什么区别str?什么时候使用String而不是str反之亦然?其中一个被弃用了吗?
我有一个未知大小的数组,我想获得该数组的一部分并将其转换为静态大小的数组:
fn pop(barry: &[u8]) -> [u8; 3] {
barry[0..3] // mismatched types: expected `[u8, ..3]` but found `&[u8]`
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
我在文档中找不到Vec<T>如何从指定范围中检索切片.
标准库中是否有类似的东西:
let a = vec![1, 2, 3, 4];
let suba = a.subvector(0, 2); // Contains [1, 2];
Run Code Online (Sandbox Code Playgroud) 是否有更直接,更易读的方法来完成以下任务:
fn main() {
let a = [1, 2, 3];
let b = [4, 5, 6];
let c = [7, 8, 9];
let iter = a.iter()
.zip(b.iter())
.zip(c.iter())
.map(|((x, y), z)| (x, y, z));
}
Run Code Online (Sandbox Code Playgroud)
也就是说,如何从n个迭代中构建迭代器,从而产生n元组?
如何Option从调用者的特定生命周期中提取引用并将其传回?
具体而言,我想借用参照Box<Foo>从Bar一个具有Option<Box<Foo>>在其中.我以为我能做到:
impl Bar {
fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
match self.data {
Some(e) => Ok(&e),
None => Err(BarErr::Nope),
}
}
}
Run Code Online (Sandbox Code Playgroud)
......但结果是:
error: `e` does not live long enough
--> src/main.rs:17:28
|
17 | Some(e) => Ok(&e),
| ^ does not live long enough
18 | None => Err(BarErr::Nope),
19 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the …Run Code Online (Sandbox Code Playgroud) 我试图了解引用和Box<T>工作方式。让我们考虑一个代码示例:
fn main() {
let x = 5;
let y = &x;
assert_eq!(5, x);
assert_eq!(5, *y);
}
Run Code Online (Sandbox Code Playgroud)
在我的想象中,Rust 将内存中的值保存为:
考虑第二个代码片段Box<T>:
fn main() {
let x = 5;
let y = Box::new(x);
assert_eq!(5, x);
assert_eq!(5, *y);
}
Run Code Online (Sandbox Code Playgroud)
将如何x存储Box?内存是什么样子的?
上面的例子来自使用DerefTrait处理像常规引用一样的智能指针。对于第二个例子,本书将其解释为:
y示例15-7 和示例15-6 之间的唯一区别是,这里我们设置为指向 in 值的框的实例,x而不是指向 值的引用x。
这是否意味着y在框中直接指向 value 5?
我想构建一个将列表拆分为两个的函数:一个列表包含原始列表中满足某个谓词的元素,另一个列表包含所有不满足某个谓词的元素.以下是我的尝试:
fn split_filter<T: Clone + Sized>(a: &Vec<T>, f: Fn(&T) -> bool) -> (Vec<T>, Vec<T>) {
let i: Vec<T> = vec![];
let e: Vec<T> = vec![];
for u in a.iter().cloned() {
if f(&u) {
i.push(u)
} else {
e.push(u)
}
}
return (i, e);
}
fn main() {
let v = vec![10, 40, 30, 20, 60, 50];
println!("{:?}", split_filter(&v, |&a| a % 3 == 0));
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到两个错误:
error[E0277]: the trait bound `for<'r> std::ops::Fn(&'r T) -> bool + 'static: std::marker::Sized` is not …Run Code Online (Sandbox Code Playgroud) 我必须迭代键,通过键在 HashMap 中找到值,可能在找到的结构中做一些繁重的计算作为一个值(懒惰 => 改变结构)并在 Rust 中缓存返回它。
我收到以下错误消息:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:25:26
|
23 | fn it(&mut self) -> Option<&Box<Calculation>> {
| - let's call the lifetime of this reference `'1`
24 | for key in vec!["1","2","3"] {
25 | let result = self.find(&key.to_owned());
| ^^^^ `*self` was mutably borrowed here in the previous iteration of the loop
...
28 | return result
| ------ returning this value requires that …Run Code Online (Sandbox Code Playgroud) 如何在闭包中调用方法?get_access_token方法可以基于以下内容设置新的访问令牌self.get_base_url():
fn fetch_access_token(_base_url: &String) -> String {
String::new()
}
fn get_env_url() -> String {
String::new()
}
pub struct App {
pub base_url: Option<String>,
pub access_token: Option<String>,
}
impl App {
pub fn new() -> App {
App {
base_url: None,
access_token: None,
}
}
pub fn get_base_url(&mut self) -> &String {
self.base_url.get_or_insert_with(|| get_env_url())
}
pub fn get_access_token(&mut self) -> &String {
self.access_token
.get_or_insert_with(|| fetch_access_token(self.get_base_url()))
}
}
fn main() {}
Run Code Online (Sandbox Code Playgroud)
错误:
锈2015
fn fetch_access_token(_base_url: &String) -> String …Run Code Online (Sandbox Code Playgroud) 我有很多 4KiB 缓冲区,它们有 50% 的机会只包含零值。非零缓冲区通常在缓冲区的早期有一个非零字节。
fn is_zero(buf: &Vec<u8>) -> bool {
for byte in buf.into_iter() {
if *byte != 0 {
return false;
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
这是检查 Rust 的一种高效方式--release吗?(我正在处理许多 GB 的数据。)
(在 C 版本中,我unsigned long long在检查之前将缓冲区强制转换为。考虑到 SSE 等,这可能不是我能做的最好的事情。)