我在浏览Serde源时遇到了这个missing_field函数:
/// Report that the struct has a field that wasn't deserialized
fn missing_field<V>(&mut self, field: &'static str) -> Result<V, Self::Error>
where V: Deserialize,
{
Err(Error::missing_field(field))
}
Run Code Online (Sandbox Code Playgroud)
为什么这有用?为什么Result要无条件地返回Err?
因为您不包含该函数的上下文:
pub trait MapVisitor {
// ...
fn missing_field<V>(&mut self, field: &'static str) -> Result<V, Self::Error>
where V: Deserialize,
{
Err(Error::missing_field(field))
}
}
Run Code Online (Sandbox Code Playgroud)
这是默认的特征方法.实现此特征的每个类型都将免费获得此方法,如果它们没有做任何特殊操作,但可以选择重新实现它.据推测,大多数实现都不会实现该方法,但它也可能只是一个理智的默认值.