该程序因无限递归而死亡:
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) 推荐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) 我有一些代码,其中有许多完全限定语法的实例;举个例子:
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)
有什么好的方法可以让我别名 …
我有以下代码:
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 中实现两个具有冲突方法名称的特征?我知道它会给你一个multiple applicable methods in scope
错误,但是有没有办法解决这个问题?例如,某些语言通过允许您显式指定应优先使用哪种方法来处理多重继承