相关疑难解决方法(0)

如何将矢量与其自身的反转版本进行比较?

为什么不编译?

fn isPalindrome<T>(v: Vec<T>) -> bool {
  return v.reverse() == v;
}
Run Code Online (Sandbox Code Playgroud)

我明白了

error[E0308]: mismatched types
 --> src/main.rs:2:25
  |
2 |   return v.reverse() == v;
  |                         ^ expected (), found struct `std::vec::Vec`
  |
  = note: expected type `()`
             found type `std::vec::Vec<T>`
Run Code Online (Sandbox Code Playgroud)

equality rust

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

无法摆脱Rust中的借来的内容

pub struct Character {
    name: String,
    hp: i32,
    level: i32,
    xp: i32,
    xp_needed: i32,
    gold: i32
}

impl Character {
    pub fn new(name: String) -> Character {
        let mut rng = thread_rng();

        let hp: i32 = rng.gen_range(12, 75);
        let gold: i32 = rng.gen_range(10, 50);

        Character { name: name, hp: hp, level: 1, xp: 0, gold: gold, xp_needed: 100 }
    }

    pub fn get_name(&self) -> String {
        self.name
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

我到底是怎么违反规则的呢?

在高层次上,这对Rust来说是违规的.你不能转让借来的东西的所有权,因为你不拥有它.

嗯,不是吗?我有其他功能,如:

pub fn get_hp(&self) -> i32 { …
Run Code Online (Sandbox Code Playgroud)

rust

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

如何修复丢失的生命周期说明符?

我有一个非常简单的方法.第一个参数采用向量组件("A",5,0),我将它与另一个向量的每个元素进行比较,看它们是否具有相同的(_,5,_),然后打印出找到的元素的字符串.

比较("A",5,0)和("Q",5,2)应打印出Q.

fn is_same_space(x: &str, y1: i32, p: i32, vector: &Vec<(&str, i32, i32)>) -> (&str) {
    let mut foundString = "";

    for i in 0..vector.len() {

        if y1 == vector[i].1 {
            foundString = vector[i].0;
        }

    }
    foundString    
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到此错误

error[E0106]: missing lifetime specifier
 --> src/main.rs:1:80
  |
1 | fn is_same_space(x: &str, y1: i32, p: i32, vector: &Vec<(&str, i32, i32)>) -> (&str) {
  |                                                                                ^ expected lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the …
Run Code Online (Sandbox Code Playgroud)

lifetime rust

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

特征能否保证某些类型属性(例如向量)为非空?

想象一下我有这样的功能:

fn min_max_difference(row: &Vec<u32>) -> u32 {
    let mut min_elem: u32 = row[0];
    let mut max_elem: u32 = min_elem;

    for &element in row.iter().skip(1) {
        if element < min_elem {
            min_elem = element;
        } else if element > max_elem {
            max_elem = element;
        }
    }

    result = max_elem - min_elem;
}

fn execute_row_operation(row: &Vec<u32>, operation: Fn(&Vec<u32>) -> u32) -> Option<(u32, u32)> {
    let mut result = None;

    if row.len() > 0 {
        result = operation(row);
    }

    result
}
Run Code Online (Sandbox Code Playgroud)

请注意,if块 …

traits rust

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

如何在一行中连接不可变向量?

我有不可变的向量ab其中元素的复制成本很低,我想创建一个向量来形成这些现有向量的串联而不改变它们 (*)。

如果其中一个向量是可变的则较早的问题解决了这个问题,因此一个明显的答案是首先克隆向量a,例如

let mut r = a.clone();
r.extend(&b);
Run Code Online (Sandbox Code Playgroud)

但这似乎既不优雅也不高效(扩展很容易导致不必要的重新分配,对吧?)。我(作为 Rust 菜鸟)提出(修正后的)最佳选择是:

fn cat(a: &Vec<i32>, b: &Vec<i32>) -> Vec<i32> {
    let mut r = Vec::<i32>::with_capacity(a.len() + b.len());
    r.extend(a);
    r.extend(b);
    r
}
Run Code Online (Sandbox Code Playgroud)

由于元素复制起来很便宜,因此对于字符串向量更通用问题的答案应该适用于这里,但vec![a, b].concat()只有当您通过将向量移动到向量中来构造向量向量时,这似乎才有效,因为会vec![&a, &b].concat()产生“未concat找到命名的方法”。

对于这项看似简单的工作,即使它不是最佳的,是否有一种单行方式?


(*) 原来“不改变”有两种含义:

  • 只是不可变的,这在 Rust 中意味着如果代码编译,它不会看到具有更改值的变量;但变量可能会被移出,进一步或未来的代码不能再使用它
  • 实际上是只读的,保留变量不变以供进一步或将来的代码使用

vector concatenation rust

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

在Rust中返回递归闭包

我有以下高阶函数

fn ensure_tonicty(tone_fn: &fn(&f64, &f64) -> bool) -> impl Fn(&Vec<f64>) -> bool {
    return |floats: &Vec<f64>| -> bool {
        let first = floats.first().unwrap();
        let rest = &floats[1..];
        fn f(tone_fn: &fn(&f64, &f64) -> bool, prev: &f64, xs: &[f64]) -> bool {
            match xs.first() {
                Some(x) => tone_fn(prev, x) && f(tone_fn, x, &xs[1..]),
                None => true,
            }
        };
        return f(tone_fn, first, rest);
    };
}
Run Code Online (Sandbox Code Playgroud)

我的目标是返回此lambda。我不知道如何有效地tone_fn在这里使用。

上面的代码出错了:

error[E0621]: explicit lifetime required in the type of `tone_fn`
 --> src/lib.rs:1:56
  |
1 | …
Run Code Online (Sandbox Code Playgroud)

recursion closures reference lifetime rust

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

你如何将 Vec&lt;&amp;mut T&gt; 转换为 Vec&lt;&amp;T&gt;?

我有一个可变引用向量:

struct T;
let mut mut_vec: Vec<&mut T> = vec![];
Run Code Online (Sandbox Code Playgroud)

我如何将它(的副本)传递给一个采用不可变引用向量的函数?

fn cool_func(mut immut_vec: Vec<&T>) {}
Run Code Online (Sandbox Code Playgroud)

casting rust

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

Rust关于Vec的Reduce方法参考

我正在尝试将 Vec 的引用减少到其总和,以便我可以计算其平均值。不过,我遇到了编译器问题,并且我没有遵循如何不正确借用/引用事物的情况。

// Given a list of integers, use a vector and return the mean (the average value), median (when sorted, the value in the middle position), and mode (the value that occurs most often; a hash map will be helpful here) of the list.
fn main() {
    let list_of_integers = vec![200, -6_000, 3, 0, 23, 99, -1];

    let mean_ans = mean(&list_of_integers);
    // Other code that will also use list_of_integers hence why I want to reference list_of_integers so it …
Run Code Online (Sandbox Code Playgroud)

functional-programming reference rust rust-cargo borrow-checker

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

为什么没有从 UTF8 编码数组创建字符串的专用方法?

我需要String从字节数组(不是Vec)构造。这有效:

let buf2 = [30, 40, 50];
let string2 = std::str::from_utf8(&buf2).unwrap().to_string();
Run Code Online (Sandbox Code Playgroud)
  1. 为什么没有专门的数组/切片方法String
  2. 为什么from_utf8不是泛型的参数?
  3. 上面的片段是惯用的 Rust 吗?

我最终不需要String&str,但问题仍然存在。

rust

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

If expressions that yield either value or reference?

I have this pattern that shows up every now and then, but I haven't found a nice way to implement it "correct".

What it is, is I have some variable passed into my function by reference. I don't need to mutate it, I don't need to transfer ownership, I just look at its contents.

However, if the contents are in some state, replace the value with a default value.

For instance say my function accepts a &Vec<String> and if the …

rust

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