This works:
use std::error::Error;
fn main() {
let _: Box<dyn Error> = "test".into();
}
Run Code Online (Sandbox Code Playgroud)
But this gives an error:
use std::error::Error;
fn main() {
let _ = "test".into::<Box<dyn Error>>();
}
Run Code Online (Sandbox Code Playgroud)
use std::error::Error;
fn main() {
let _: Box<dyn Error> = "test".into();
}
Run Code Online (Sandbox Code Playgroud)
Why?
这来自Into特征定义:
pub trait Into<T> {
fn into(self) -> T;
}
Run Code Online (Sandbox Code Playgroud)
如您所见,into没有泛型参数,但它来自特征定义本身。正确的完全限定语法是:
use std::error::Error;
fn main() {
let _ = Into::<Box<dyn Error>>::into("asd");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
133 次 |
| 最近记录: |