相关疑难解决方法(0)

当trait和struct使用相同的方法名时,如何调用方法?

该程序因无限递归而死亡:

use std::any::Any;

trait Foo {
    fn get(&self, index: usize) -> Option<&Any>;
}

impl Foo for Vec<i32> {
    fn get(&self, index: usize) -> Option<&Any> {
        Vec::get(self, index).map(|v| v as &Any)
    }
}

fn main() {
    let v: Vec<i32> = vec![1, 2, 4];
    println!("Results: {:?}", v.get(0))
}
Run Code Online (Sandbox Code Playgroud)

编译器本身警告:

warning: function cannot return without recurring
  --> src/main.rs:8:5
   |
8  |       fn get(&self, index: usize) -> Option<&Any> {
   |  _____^ starting here...
9  | |         Vec::get(self, index).map(|v| v as &Any)
10 | | …
Run Code Online (Sandbox Code Playgroud)

rust

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

在Rust中推荐使用`use`声明的地方在哪里?

推荐use声明的推荐位置在哪里?我在书中,常见问题解答,邮件列表或在线论坛中找不到任何决定性的答案.我正在Rust开始一个新项目,我宁愿立刻采取正确的方法.

建议使用以下两种方法之一吗?它只是用于"别名"的东西还是它做的更多,比如如果以前没有使用它就初始化模块?

use std::io;
use std::io::Write;

fn some_func() -> () {
    [...] // We assume we need std::io here
}

fn some_other_func() -> () {
    [...] // We assume we need std::io and std::io::Write here
}
Run Code Online (Sandbox Code Playgroud)

要么

fn some_func() -> () {
    use std::io;
    [...] // We assume we need std::io here
}

fn some_other_func() -> () {
    use std::io;
    use std::io::Write;
    [...] // We assume we need std::io and std::io::Write here
}
Run Code Online (Sandbox Code Playgroud)

rust

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

我可以别名完全限定的语法吗?

我有一些代码,其中有许多完全限定语法的实例;举个例子:

mod hal {
    pub trait Backend {
        type Device;
    }
}

mod back {
    pub struct Backend {}

    impl ::hal::Backend for Backend {
        type Device = i32;
    }
}

fn main() {
    let d: back::Backend::Device = 0;
}
Run Code Online (Sandbox Code Playgroud)

操场

为了避免错误,例如:

mod hal {
    pub trait Backend {
        type Device;
    }
}

mod back {
    pub struct Backend {}

    impl ::hal::Backend for Backend {
        type Device = i32;
    }
}

fn main() {
    let d: back::Backend::Device = 0;
}
Run Code Online (Sandbox Code Playgroud)

有什么好的方法可以让我别名 …

syntax rust type-alias

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

如何消除泛型特征方法调用的歧义?

我有以下代码:

struct X { i: i32 }

trait MyTrait<T> {
    fn hello(&self);
}

impl MyTrait<i32> for X {
    fn hello(&self) { println!("I'm an i32") }
}

impl MyTrait<String> for X {
    fn hello(&self) { println!("I'm a String") }
}

fn main() {
    let f = X { i: 0 };
    f.hello();
}
Run Code Online (Sandbox Code Playgroud)

显然不能编译,因为编译器无法消除f.hello()属于哪个特征的歧义。所以我得到了错误

error[E0282]: type annotations needed
  --> src\main.rs:17:7
   |
17 |     f.hello();
   |       ^^^^^ cannot infer type for type parameter `T` declared on the trait `MyTrait`
Run Code Online (Sandbox Code Playgroud)

有没有什么办法来注释的类型 …

rust

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

一个结构可以在 Rust 中实现两个具有冲突方法名称的特征吗?

是否可以在 Rust 中实现两个具有冲突方法名称的特征?我知道它会给你一个multiple applicable methods in scope错误,但是有没有办法解决这个问题?例如,某些语言通过允许您显式指定应优先使用哪种方法来处理多重继承

traits rust

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

标签 统计

rust ×5

syntax ×1

traits ×1

type-alias ×1