该程序因无限递归而死亡:
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) 我想write_fmt在两种不同类型的对象上使用该方法:
use std::fmt::Write;
use std::io::Write;
fn main() {
let mut a = String::new();
let mut b = std::fs::File::create("test").unwrap();
a.write_fmt(format_args!("hello"));
b.write_fmt(format_args!("hello"));
}
Run Code Online (Sandbox Code Playgroud)
我在使用时遇到错误,Write因为它们的名称相同:
error[E0252]: a trait named `Write` has already been imported in this module
--> src/main.rs:8:5
|
7 | use std::fmt::Write;
| --------------- previous import of `Write` here
8 | use std::io::Write;
| ^^^^^^^^^^^^^^ `Write` already imported
a.write_fmt(format_args!("hello"));
b.write_fmt(format_args!("hello"));
Run Code Online (Sandbox Code Playgroud)
或者我得到一个错误,说该特征不可用:
error[E0599]: no method named `write_fmt` found for type `std::fs::File` in the current scope
--> src/main.rs:76:4
| …Run Code Online (Sandbox Code Playgroud) rust ×2