相关疑难解决方法(0)

为什么我不能在解构变量后调用方法但是如果直接访问该字段我可以吗?

以下没有编译:

use std::any::Any;

pub trait CloneBox: Any {
    fn clone_box(&self) -> Box<dyn CloneBox>;
}

impl<T> CloneBox for T
where
    T: Any + Clone,
{
    fn clone_box(&self) -> Box<dyn CloneBox> {
        Box::new(self.clone())
    }
}

struct Foo(Box<dyn CloneBox>);

impl Clone for Foo {
    fn clone(&self) -> Self {
        let Foo(b) = self;
        Foo(b.clone_box())
    }
}
Run Code Online (Sandbox Code Playgroud)

错误信息:

error[E0495]: cannot infer an appropriate lifetime for pattern due to conflicting requirements
  --> src/lib.rs:20:17
   |
20 |         let Foo(b) = self;
   |                 ^
   |
note: …
Run Code Online (Sandbox Code Playgroud)

pattern-matching lifetime rust

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

Rust函数如何修改数组索引的值?

我的目标是让Rust函数f增加一个数组元素x,并增加索引i:

fn main() {
    let mut x: [usize; 3] = [1; 3];
    let mut i: usize = 1;
    f(&mut i, &mut x);
    println!("\nWant i = 2, and i = {}", i);
    println!("\nWant x = [1,2,1], and x = {:?}", x);
} // end main

fn f(i: &mut usize, x: &mut [usize]) {
    x[i] += 1;
    i += 1;
} // end f
Run Code Online (Sandbox Code Playgroud)

编译器报告以下错误:

error[E0277]: the trait bound `&mut usize: std::slice::SliceIndex<[usize]>` is not satisfied
  --> …
Run Code Online (Sandbox Code Playgroud)

parameters function increment rust

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

移出泛型类型的共享引用

我正在尝试创建一个函数,该函数使用迭代器&[Vec<u64>]i64每行中最大的一个返回元组“坐标”向量。我有它在具体类型上工作,但我希望它是通用的,T并且限制为可迭代类型。到目前为止我的代码:

fn find_largest_per_row<T>(input: &[T]) -> Vec<(usize, usize)> 
where
    T: IntoIterator<Item = u64>,
{
    input
        .iter()
        .enumerate()
        .map(|(r, v)| {
            v.into_iter()
                .enumerate()
                .max_by_key(|&(_, v)| v)
                .map(|(c, _)| (r, c))
                .unwrap()
        })
        .collect::<Vec<_>>()
}
Run Code Online (Sandbox Code Playgroud)

我越来越:

fn find_largest_per_row<T>(input: &[T]) -> Vec<(usize, usize)> 
where
    T: IntoIterator<Item = u64>,
{
    input
        .iter()
        .enumerate()
        .map(|(r, v)| {
            v.into_iter()
                .enumerate()
                .max_by_key(|&(_, v)| v)
                .map(|(c, _)| (r, c))
                .unwrap()
        })
        .collect::<Vec<_>>()
}
Run Code Online (Sandbox Code Playgroud)

我该如何解决?我意识到T是一个参考,所以我尝试了.cloned(),但这没有用。

另外,对于IntoIterator<Item=u64>,我需要指定u64还是可以提供更通用的东西?

generics traits move-semantics rust

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

Rust:为什么当“self:&amp;Self”时“self”不是引用?

根据Rust Lang 编程书籍,我们知道:

&self 实际上是 self 的缩写:&Self

但是,从下面的示例( )中,根据错误消息,fn get_name我们编写的self: &Self, but不是引用而是对象本身。self为什么在这种情况下没有self参考?那么其中的&符号是做什么用的&Self呢?

示例:一个简单的结构体,其方法返回一个人的名字

struct Person {
    name: String
}

impl Person {
    fn new(name: &str) -> Person {
        Person {
            name: name.to_string()
        }
    }

    fn get_name(self: &Self) -> &String {
        self.name // Error: expected `&std::string::String`, found struct `std::string::String`
    }
}
Run Code Online (Sandbox Code Playgroud)

reference self rust

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

类型 '()' 不能被取消引用

有人能解释一下为什么它说它*profession是一个单位类型而它是一个向量吗?

use hashbrown::HashMap;

fn main() {
    let mut sphere: HashMap<String, Vec<&str>> = HashMap::new();
    sphere.insert(String::from("junior"), vec![]);
    sphere.insert(String::from("Middle"), vec![]);
    sphere.insert(String::from("Senior"), vec![]);
    loop {
        println!();
        let mut input = String::new();
        std::io::stdin()
            .read_line(&mut input)
            .expect("What the hell this doesn't work!?");
        if input.trim() == "stop" {
            break;
        }
        let splited_data: Vec<&str> = input.split(" to ").collect();
        let person = splited_data[0];
        let category = splited_data[1].to_string();
        let professions = sphere.entry(category.to_string()).or_insert(vec![]);
        *professions.push(person);
    }
}
Run Code Online (Sandbox Code Playgroud)
error[E0614]: type `()` cannot be dereferenced
  --> src/lib.rs:21:9
   |
21 |         *professions.push(person);
   | …
Run Code Online (Sandbox Code Playgroud)

hashmap rust

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