我了解您无法实现Default当前板条箱中未实现的类型的特征。为什么不能将这些类型别名为内部使用的类型并执行此操作?
这不起作用(游乐场):
use std::collections::HashMap;
pub type MyPortMappings = HashMap<&'static str, (u32, &'static str)>;
impl Default for MyPortMappings {
fn default() -> Self {
let mut m = HashMap::new();
m.insert("ftp", (21, "File Transfer Protocol"));
m.insert("http", (80, "Hypertext Transfer Protocol"));
m
}
}
Run Code Online (Sandbox Code Playgroud)
error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate
--> src/lib.rs:5:1
|
5 | impl Default for MyPortMappings {
| ^^^^^^^^^^^^^^^^^--------------
| | |
| | `HashMap` is not defined in the current crate
| impl doesn't use only types from inside the current crate
|
= note: define and implement a trait or new type instead
Run Code Online (Sandbox Code Playgroud)
在自己的控制下实施默认设置是否没有意义?
\xe2\x80\x99s 因为类型别名只是别名,而不是单独的类型。您需要使用struct、enum或来创建自己的包装器union。
这是使用newtype习惯用法的另一种选择:
\npub struct MyPortMappings(HashMap<&\'static str, (u32, &\'static str)>);\n\nimpl MyPortMapping {\n // ... boilerplate and associated items...\n}\n\nimpl Default for MyPortMappings {\n fn default() -> Self {\n let mut m = HashMap::new();\n m.insert("ftp", (21, "File Transfer Protocol"));\n m.insert("http", (80, "Hypertext Transfer Protocol"));\n Self(m)\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n您还可以使用Delegate包将字段的方法委托给结构体本身。
\n但就您而言,最好只是实现一个返回所需值的函数,或者如果您需要将其作为方法,则创建一个特征。在这种情况下,不需要创建另一种类型。
\n