相关疑难解决方法(0)

什么是非词汇生命?

Rust有一个与非词汇生命周期相关的RFC,已被批准在该语言中实现了很长时间.最近,Rust对此功能的支持有了很大改进,并且被认为是完整的.

我的问题是:非词汇生命究竟是什么?

lifetime rust lifetime-scoping

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

根据最后一个元素将某些东西推入向量

我想得到一个向量的最后一个元素并用它来确定下一个要推入的元素.这是一个例子,它不起作用,但它显示了我想要实现的目标:

let mut vector: Vec<i32> = Vec::new();

if let Some(last_value) = vector.last() {
    vector.push(*last_value + 1);
}
Run Code Online (Sandbox Code Playgroud)

push当矢量也被不可靠地借用时我无法使用:

error[E0502]: cannot borrow `vector` as mutable because it is also borrowed as immutable
 --> src/main.rs:5:9
  |
4 |     if let Some(last_value) = vector.last() {
  |                               ------ immutable borrow occurs here
5 |         vector.push(*last_value + 1);
  |         ^^^^^^ mutable borrow occurs here
6 |     }
  |     - immutable borrow ends here
Run Code Online (Sandbox Code Playgroud)

这样做有什么好办法?

rust borrow-checker

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

为什么 Rust 想要一次多次借用一个可变变量?

我正在尝试在 Rust 中实现一个动态编程问题以熟悉该语言。像许多动态规划问题一样,这使用记忆化来减少运行时间。不幸的是,我的第一遍解决方案会产生错误。我已将代码缩减为以下内容。警告 - 现在有点荒谬:

use std::collections::HashMap;

fn repro<'m>(memo: &'m mut HashMap<i32, Vec<i32>>) -> Option<&'m Vec<i32>> {
    {
        let script_a = repro(memo);
        let script_b = repro(memo);
    }

    memo.get(&0)
}

fn main() {}
Run Code Online (Sandbox Code Playgroud)

编译错误是:

use std::collections::HashMap;

fn repro<'m>(memo: &'m mut HashMap<i32, Vec<i32>>) -> Option<&'m Vec<i32>> {
    {
        let script_a = repro(memo);
        let script_b = repro(memo);
    }

    memo.get(&0)
}

fn main() {}
Run Code Online (Sandbox Code Playgroud)

为什么变量被memo多次借用?在我看来,它应该在我计算时借用一次script_a,然后借用结束,然后再次借用script_b

rust

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

我应该如何重构我的图形代码以避免“一次不能多次借用可变变量”错误?

我有一个成功编译的简单图表:

use std::collections::HashMap;

type Key = usize;
type Weight = usize;

#[derive(Debug)]
pub struct Node<T> {
    key: Key,
    value: T,
}
impl<T> Node<T> {
    fn new(key: Key, value: T) -> Self {
        Node {
            key: key,
            value: value,
        }
    }
}

#[derive(Debug)]
pub struct Graph<T> {
    map: HashMap<Key, HashMap<Key, Weight>>,
    list: HashMap<Key, Node<T>>,
    next_key: Key,
}
impl<T> Graph<T> {
    pub fn new() -> Self {
        Graph {
            map: HashMap::new(),
            list: HashMap::new(),
            next_key: 0,
        }
    }
    pub fn add_node(&mut self, value: …
Run Code Online (Sandbox Code Playgroud)

lifetime rust borrowing

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

为什么在函数调用完成后,可变借用的生命周期不会结束?

我正在为halite.io写一个机器人,并且在理解借用的一些影响方面遇到了问题.这是无法编译的代码:

let scanLoc = hlt::types::Location {
    x: oflow(coord.0 + l.x as i32, game_map.width),
    y: oflow(coord.1 + l.y as i32, game_map.width),
};
let scan = game_map.get_site(scanLoc, types::STILL);
if (&scan.owner != id) | (scan.owner != 0u8) {
    let ang = game_map.get_angle(l, scanLoc);
    debug!("angle b/w: {}", ang);
    return (l, 2);
}
Run Code Online (Sandbox Code Playgroud)

这是编译器错误:

error[E0502]: cannot borrow `*game_map` as immutable because it is also borrowed as mutable
   --> src/MyBot.rs:112:27
      |
  110 |             let scan = game_map.get_site(scanLoc, types::STILL);
      |                        -------- mutable borrow occurs here
  111 | …
Run Code Online (Sandbox Code Playgroud)

rust

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

如何在 Vec 中存储引用并稍后在 Rust 中使用它?

我需要创建一个 Vec 来跟踪我正在创建的对象并更改其状态以供以后使用。但是,如果我在获取存储在 vec 上的对象时使用克隆,它的状态不会更新,我该怎么做?

#[derive(Debug, Clone)]
struct Movement {
  x: i32,
  y: i32,
}

fn main() {
   let mut current = Some(Movement { x: 1, y: 2 });

   let mut stack = Vec::new();

   stack.push(&current);

   current.as_mut().unwrap().x = 2;

   println!("m: {:?}", current);
   println!("stack.m: {:?}", stack.pop());
   current = None;
}
Run Code Online (Sandbox Code Playgroud)

rust

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

不能将`*x`借用为可变因为它也被借用为不可变的

我正在制作一个组合优化项目来学习Rust,我遇到了一个问题,我无法解决自己...

我有两个功能:

pub fn get_pareto_front_offline<'a>(scheduling_jobs: &'a Vec<Vec<u32>>, costs_vector: &'a Vec<(u32, u32)>) -> Vec<(&'a Vec<u32>, &'a (u32, u32))> {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

pub fn pareto_approach_offline<'a>(list_of_jobs: &'a mut Vec<Vec<u32>>, neighborhood: &'a mut Vec<Vec<u32>>, costs: &'a Vec<(u32, u32)>) -> Vec<(&'a Vec<u32>, &'a (u32, u32))> {
    let pareto_front = get_pareto_front_offline(neighborhood, costs);

    loop {
        if pareto_front == vec![] {
            break;
        }

        neighborhood.clear();

        for front in pareto_front.iter() {
            neighborhood.push((front.0).clone());
        }
    }

    pareto_front
}
Run Code Online (Sandbox Code Playgroud)

我有一个问题,因为编译器告诉我:

cannot borrow '*neighborhood' as mutable because it is also borrowed as …
Run Code Online (Sandbox Code Playgroud)

mutable immutability rust borrowing

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

为什么我会收到错误"不能多次借x可变"?

我在Rust中实现了一个解析器.我必须更新前瞻的索引,但是当我收到错误self.get()后调用时self.current():

cannot borrow *self as mutable more than once at a time
Run Code Online (Sandbox Code Playgroud)

这是令人困惑的,因为我是Rust的新手.

#[derive(Debug)]
pub enum Token {
    Random(String),
    Undefined(String),
}

struct Point {
    token: Vec<Token>,
    look: usize,
}

impl Point {
    pub fn init(&mut self){
        while let Some(token) = self.current(){
            println!("{:?}", token); 
            let _ = self.get();
        }
    }

    pub fn current(&mut self) -> Option<&Token> {
        self.token.get(self.look)
    }

    pub fn get(&mut self) -> Option<&Token> {
        let v = self.token.get(self.look);
        self.look += 1;
        v
    }

}

fn …
Run Code Online (Sandbox Code Playgroud)

lifetime rust

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

Rust 编译器如何生成“此处发生不可变借用”?

我正在学习 Rust,以下代码来自在线书籍 The Rust Programming Language链接

fn first_word(s: &String) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }

    &s[..]
}

fn main() {
    let mut s = String::from("hello world");

    let word = first_word(&s);

    s.clear(); // error!

    println!("the first word is: {}", word);
}

Run Code Online (Sandbox Code Playgroud)

编译器如下:

fn first_word(s: &String) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' …
Run Code Online (Sandbox Code Playgroud)

rust

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

如何将对self的可变引用转换为不可变引用以用作方法的参数?

我有以下无法编译的代码:

struct A {
    x: i32,
}

impl A {
    fn add_assign(&mut self, other: &Self) {
        self.x += other.x;
    }

    fn double(&mut self) {
        self.add_assign(self);
    }
}
Run Code Online (Sandbox Code Playgroud)

错误是:

error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
  --> src/lib.rs:11:9
   |
11 |         self.add_assign(self);
   |         ^^^^^----------^----^
   |         |    |          |
   |         |    |          immutable borrow occurs here
   |         |    immutable borrow later used by call
   |         mutable borrow occurs here
Run Code Online (Sandbox Code Playgroud)

如何传递self作为参数add_assign?我已经试过&self, …

methods reference immutability rust

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