如何复制&[u8]切片的内容?
我正在尝试编写一个函数,它将缓冲区作为输入,并使用给定键对每个字节进行异或,并返回最终结果.
我不希望它破坏输入缓冲区.
pub fn xor_buffer(buffer_in: &[u8], key: char) -> &[u8] {
let mut buffer_out = buffer_in.clone();
for byte in &mut buffer_out[..] {
*byte ^= key as u8;
}
buffer_out
}
Run Code Online (Sandbox Code Playgroud)
此代码生成以下编译时错误:
src/test.rs:29:22: 29:32 error: cannot borrow immutable borrowed content `*buffer_out` as mutable
src/test.rs:29 for byte in &mut buffer_out[..] {
^~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
我知道我必须做错事.
任何帮助都会得到赞赏.
我不明白为什么我从这段代码中得到以下编译器错误:
struct Superhero<'a> { name: &'a String, power: &'a i32 } // 1
// 2
fn main() { // 3
let n = "Bruce Wayne".to_string(); // 4
let r; // 5
{ // 6
let p = 98; // 7
{ // 8
let hero = Superhero{ name: &n, power: &p }; // 9
r = hero.name; // 10
} // 11
println!("{}", r); // 12
} // 13
} // 14
Run Code Online (Sandbox Code Playgroud)
编译器错误: rustc 1.27.1 (5f2b325f6 2018-07-07)
error[E0597]: `p` does …Run Code Online (Sandbox Code Playgroud) 我有一些设计问题,我想用安全的 Rust 来解决,但我一直无法找到可行的解决方案。我不能使用 aRefCell因为你不能得到 & 对数据的引用,只有Ref/ RefMut。
use std::cell::RefCell;
use std::rc::Rc;
struct LibraryStruct {}
impl LibraryStruct {
fn function(&self, _a: &TraitFromLibrary) {}
}
trait TraitFromLibrary {
fn trait_function(&self, library_struct: LibraryStruct);
}
// I don't want to copy this, bad performance
struct A {
// fields...
}
impl TraitFromLibrary for A {
fn trait_function(&self, library_struct: LibraryStruct) {
// custom A stuff
}
}
// B manipulates A's in data
struct B {
data: Vec<A>, …Run Code Online (Sandbox Code Playgroud) 我正在研究Rust by Example并从"Alias"页面运行代码:
struct Point {
x: i32,
y: i32,
z: i32,
}
fn main() {
let mut point = Point { x: 0, y: 0, z: 0 };
{
let borrowed_point = &point;
let another_borrow = &point;
// Data can be accessed via the references and the original owner
println!(
"Point has coordinates: ({}, {}, {})",
borrowed_point.x, another_borrow.y, point.z
);
// Error! Can't borrow point as mutable because it's currently
// borrowed as immutable.
let …Run Code Online (Sandbox Code Playgroud) 我正在从No Starch Press的《 Rust编程语言》一书中学习Rust,但是遇到了一个问题,即编译器的行为与第4页第4章中的解释不符。77。
本书的第4章正在讨论所有权,第p页的示例。77与此类似,但是没有最后的println!()输入main()(我还添加了注释和第76页的功能以创建MCVE)。我还创建了一个游乐场。
fn main() {
let mut s = String::from("Hello world!");
let word = first_word(&s);
// according to book, compiler should not allow this mutable borrow
// since I'm already borrowing as immutable, but it does allow it
s.clear();
// but of course I do get error here about immutable borrow later being
// used here, but shouldn't it have errored on the clear() operation before
// …Run Code Online (Sandbox Code Playgroud) 我想编写一个函数,该函数接受“ str”,“ String”和借用的“&String”。
我编写了以下2个函数:
fn accept_str_and_ref_string(value: &str)
{
println!("value: {}", value);
}
fn accept_str_and_string<S: Into<String>>(value: S)
{
let string_value: String = value.into();
println!("string_value: {}", string_value);
}
fn main() {
let str_foo = "foo";
let string_foo = String::from("foo");
accept_str_and_ref_string(str_foo);
accept_str_and_ref_string(&string_foo);
accept_str_and_string(str_foo);
accept_str_and_string(string_foo);
}
Run Code Online (Sandbox Code Playgroud)
但我想要1功能,所以我可以做到这一点:
accept_all_strings(str_foo);
accept_all_strings(&string_foo);
accept_all_strings(string_foo);
Run Code Online (Sandbox Code Playgroud)
这可能吗?
我有一个函数应该从单词列表中选择随机单词:
pub fn random_words<'a, I, R>(rng: &mut R, n: usize, words: I) -> Vec<&'a str>
where
I: IntoIterator<Item = &'a str>,
R: rand::Rng,
{
rand::sample(rng, words.into_iter(), n)
}
Run Code Online (Sandbox Code Playgroud)
据推测这是一个合理的签名:因为我实际上并不需要函数中的字符串本身,所以处理引用比完全使用更有效String.
如何优雅高效地将Vec<String>程序从文件中读取的单词传递给此函数?我得到了这个:
extern crate rand;
fn main() {
let mut rng = rand::thread_rng();
let wordlist: Vec<String> = vec!["a".to_string(), "b".to_string()];
let words = random_words(&mut rng, 4, wordlist.iter().map(|s| s.as_ref()));
}
Run Code Online (Sandbox Code Playgroud)
这是正确的方法吗?我是否可以在没有明确映射单词列表的情况下编写此代码来获取引用?
在实现 LazyList 的一个版本(一个不可变的延迟计算的记忆单链表,就像 Haskell 列表)时,我遇到了一个实现问题,IntoIterator因为代码在我认为应该删除引用时却没有删除。以下代码已被简化,只是为了显示问题;因此,它不是通用的,也不包括与实现无关的所有方法IntoIterator:
use std::cell::UnsafeCell;
use std::mem::replace;
use std::rc::Rc;
// only necessary because Box<FnOnce() -> R> doesn't yet work...
trait Invoke<R = ()> {
fn invoke(self: Box<Self>) -> R;
}
impl<'a, R, F: 'a + FnOnce() -> R> Invoke<R> for F {
#[inline(always)]
fn invoke(self: Box<F>) -> R {
(*self)()
}
}
// not thread safe
struct Lazy<'a, T: 'a>(UnsafeCell<LazyState<'a, T>>);
enum LazyState<'a, T: 'a> {
Unevaluated(Box<Invoke<T> + 'a>),
EvaluationInProgress,
Evaluated(T),
}
use self::LazyState::*; …Run Code Online (Sandbox Code Playgroud) fn count_spaces(text: Vec<u8>) -> usize {
text.split(|c| c == 32u8).count()
}
Run Code Online (Sandbox Code Playgroud)
上面的函数无法编译,并在比较时给出以下错误:
特征 `&u8: std::cmp::PartialEq` 不满足
我将其读为:“c是借用的字节,无法与常规字节进行比较”,但我一定读错了。
根据特定值拆分 a 的适当方法是什么Vec<u8>?
我确实意识到在读取文件时有一些选项,比如分割 aBufReader或者我可以将向量转换为字符串并使用str::split. 我可能会采用这样的解决方案(传递 aBufReader而不是 a Vec<u8>),但现在我只是在玩,测试东西并想知道我做错了什么。
为什么这段代码会编译?
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let x = "eee";
let &m;
{
let y = "tttt";
m = longest(&x, &y);
}
println!("ahahah: {}", m);
}
Run Code Online (Sandbox Code Playgroud)
对我来说,由于生命周期,应该存在编译错误。如果我用 编写相同的代码i64,则会出现错误。
fn ooo<'a>(x: &'a i64, y: &'a i64) -> &'a i64 {
if x > y {
x
} else {
y
}
}
fn main() {
let x = …Run Code Online (Sandbox Code Playgroud)