标签: ownership

在运行时在堆上分配缓冲区

我正在通过编写简单的二进制解码器来学习 Rust。

我正在使用BufferedReader带有byteorder crate 的 a来读取数字,但是我在读取字节缓冲区时遇到了问题。

我想将字节数据读入在运行时分配的缓冲区中。然后我想将此缓冲区的所有权传递给一个结构。当 struct 不再使用时,应释放缓冲区。

除了一些Vec::with_capacity()hacks之外,似乎没有办法在堆上分配运行时确定的大小的数组。任何想法如何使用适当的 Rust 语义来实现它?

heap memory-management ownership rust

1
推荐指数
2
解决办法
2465
查看次数

如何借用未包装的 Option<T>?

我想使用 .iter_mut()and.map()

fn calculate_distances(planes : &mut Vec<Aeroplane>, x: f64, y: f64) {
    fn calculate_distance(x1: &f64, y1: &f64, x2: &f64, y2: &f64) -> f6 { ... }
    planes.iter_mut().map(|a| if a.position.is_some() {
        let pos: &Position = &a.position.unwrap();
        a.distance = Some(calculate_distance(&x, &y, &pos.latitude, &pos.longitude));
    });
}
Run Code Online (Sandbox Code Playgroud)

Aeroplane 包含我的实例 Position结构:

struct Position {
    latitude: f64,
    longitude: f64,
}
Run Code Online (Sandbox Code Playgroud)

根据我的理解,我只是借用了位置信息并没有移出任何东西,但是借用检查器拒绝了我的代码:

fn calculate_distances(planes : &mut Vec<Aeroplane>, x: f64, y: f64) {
    fn calculate_distance(x1: &f64, y1: &f64, x2: &f64, y2: &f64) -> f6 …
Run Code Online (Sandbox Code Playgroud)

closures ownership rust

1
推荐指数
1
解决办法
1286
查看次数

如何在借用不可变值的匹配中进行变异?

我可以理解 Rust 中的借用/所有权概念,但我不知道如何解决这种情况:

use std::collections::{HashMap, HashSet};

struct Val {
    t: HashMap<u16, u16>,
    l: HashSet<u16>,
}

impl Val {
    fn new() -> Val {
        Val {
            t: HashMap::new(),
            l: HashSet::new(),
        }
    }

    fn set(&mut self, k: u16, v: u16) {
        self.t.insert(k, v);
        self.l.insert(v);
    }

    fn remove(&mut self, v: &u16) -> bool {
        self.l.remove(v)
    }

    fn do_work(&mut self, v: u16) -> bool {
        match self.t.get(&v) {
            None => false,
            Some(r) => self.remove(r),
        }
    }
}

fn main() {
    let mut v = …
Run Code Online (Sandbox Code Playgroud)

ownership rust borrowing

1
推荐指数
1
解决办法
916
查看次数

Rust - 从 `&amp;str` 转换为 `String` 并使用闭包返回

我正在阅读这本书,但我不明白为什么这个函数不能编译:

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    contents
        .lines()                           // Fetch an iterator for each line in `contents`
        .map(|x| x.to_lowercase())         // (x is now String) Convert each line to lowercase
        .filter(|x| x.contains(query))     // Filter out lines that do not contain query
        .map(|x| x.trim())                 // Eliminate extra whitespace
        .collect()                         // Consume iterator and produce Vec<&str>
}
Run Code Online (Sandbox Code Playgroud)

如果没有该to_lowercase()行,它将运行,我猜这是因为它将返回 aString而不是&str我们最后需要输出的。但是,当我将转换替换回&strlike 时:

// -- snip --
.map(|x| x.to_lowercase().to_str())
// …
Run Code Online (Sandbox Code Playgroud)

closures ownership rust borrow-checker borrowing

1
推荐指数
1
解决办法
2004
查看次数

Rust 和借用中的字符串连接

我最近一直在学习 Rust。

我偶然发现了一个真正让我烦恼的片段。

为什么这样做

    fn main() {
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = s1 + &s2;
    println!("{}",s3)
}
Run Code Online (Sandbox Code Playgroud)

而这不?

fn main() {
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = &s1 + s2;
    println!("{}",s3)
}
Run Code Online (Sandbox Code Playgroud)

先感谢您

ownership rust borrowing

1
推荐指数
1
解决办法
78
查看次数

所有权转移后的变异变量

我知道如何使代码工作我只是想知道为什么会这样。

假设有以下程序:

fn dummy(name: String) {
    let last_name = " Wang".to_string();
    name.push_str(&last_name);
    println!("Hello, {}", name);
}

fn main() {
    println!("What is your name?");
    let mut name = String::new();
    std::io::stdin().read_line(&mut name).expect("Couldn't read input!");
    name.pop();
    dummy(name);
}
Run Code Online (Sandbox Code Playgroud)

当尝试编译它时,出现以下错误:

error[E0596]: cannot borrow `name` as mutable, as it is not declared as mutable
 --> print.rs:3:5
  |
1 | fn dummy(name: String) {
  |          ---- help: consider changing this to be mutable: `mut name`
2 |     let last_name = " Wang".to_string();
3 |     name.push_str(&last_name);
  | …
Run Code Online (Sandbox Code Playgroud)

transfer ownership rust

1
推荐指数
1
解决办法
854
查看次数

尝试删除和插入 HashMap 时出现错误的可变借用 (E0502)

我是 Rust 的初学者并尝试使用HashMap<u64, u64>. 我想删除一个元素并使用修改后的值插入它:

let mut r = HashMap::new();
let mut i = 2;
...
if r.contains_key(&i) {
    let v = r.get(&i).unwrap();
    r.remove(&i);
    r.insert(i, v+1);
}
Run Code Online (Sandbox Code Playgroud)

现在,借用检查器rif-block 的三行中抱怨借用不可变,然后是可变的,然后又是不可变的。我不明白发生了什么......我猜因为get,removeinsert方法r作为隐式参数,它在三个调用中被借用。但是为什么remove调用中的这个借用是可变的呢?

hashmap ownership rust borrow-checker

1
推荐指数
1
解决办法
64
查看次数

如何在不分配内存的情况下将 Vec 一分为二?

我正在寻找类似于slice::split_at_mut. 让我们split_at用签名命名它

pub fn split_at<T>(v: Vec<T>, mid: usize) -> (Vec<T>, Vec<T>)
Run Code Online (Sandbox Code Playgroud)

以至于

let v = vec![1, 2, 3, 4];
let (first, second) = split_at(v, 2);
assert_eq!(first, vec![1, 2]);
assert_eq!(second, vec![3, 4]);
Run Code Online (Sandbox Code Playgroud)

该函数不应分配内存,只需将向量一分为二。您无需担心容量,因为结果向量不会被修改。

仅每晚使用的方法Vec::into_raw_parts似乎很有希望,但我在不允许使用此类方法的稳定发布频道上。

memory-management unsafe vector ownership rust

1
推荐指数
2
解决办法
84
查看次数

为什么 .clone() 在闭包中使用时不会阻止移动?

我正在尝试通过智能克隆和借用来优化应用程序,并且我正在观察以下行为。下面的程序将无法运行:

fn f( string: String) {
    println!("{}", string );
}

fn main() {
    let my_string: String = "ABCDE".to_string();
    f( my_string );
    f( my_string );
}
Run Code Online (Sandbox Code Playgroud)

它会生成众所周知的“移动后使用”错误。

fn f( string: String) {
    println!("{}", string );
}

fn main() {
    let my_string: String = "ABCDE".to_string();
    f( my_string );
    f( my_string );
}
Run Code Online (Sandbox Code Playgroud)

这个可以通过克隆来解决my_string。下面的程序运行良好:

fn f( string: String) {
    println!("{}", string );
}

fn main() {
    let my_string: String = "ABCDE".to_string();
    f( my_string.clone() );
    f( my_string.clone() );
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您在多线程环境中使用相同的方法,克隆就不再有帮助了。当函数调用嵌入到线程中时: …

closures ownership rust

1
推荐指数
1
解决办法
587
查看次数

如何在循环中创建结构向量

我正在尝试学习 Rust,并利用代码的出现来做到这一点。我刚刚开始并决定拥有一个包含“Elf”结构的向量,其中每个结构都包含一个向量 calory_items。

我正在尝试从文本文件创建它并具有以下代码:

use std::io::{self, BufReader};
use std::path::Path;
use std::io::prelude::*;
use std::fs::File;

struct Elf {
    calory_items: Vec<i32>
}

fn parse_meal_list(source: &str) -> Vec<Elf> {
    let file = File::open(source).unwrap();
    let file = BufReader::new(file);
    
    let mut elves: Vec<Elf> = Vec::new();
    let mut elf = Elf {
        calory_items: Vec::new()
    };

    for line in file.lines() {
        let line = line.unwrap();
        if line.is_empty() {
            // create new Elf
            if elf.calory_items.len() > 0 {
                // in case there are two empty lines
                elves.push(elf); …
Run Code Online (Sandbox Code Playgroud)

struct vector ownership rust

1
推荐指数
1
解决办法
157
查看次数