繁体   English   中英

在 Rust 中对字符串使用 TryFrom 时出错

[英]Error while using TryFrom for String in Rust

我正在尝试在下面显示的以下代码的帮助下实现 TryFrom 以将字符串转换为切片。

impl<const N: usize> TryFrom<String> for [u8; N] {
    type Error = &'static str;

    fn try_from(value: String) -> Result<[u8; N], Self::Error> {
        let val = value.as_bytes()[..];
        Ok(val)
    }
}

调用时出现编译错误

let a = String::try_from("a".to_string()) 

impl<const N: usize> TryFrom<String> for [u8; N] {
    | ^^^^^^^^^^^^^^^^^^^^^---------------^^^^^-------
    | |                    |                   |
    | |                    |                   this is not defined in the current crate because arrays are always foreign
    | |                    `std::string::String` is not defined in the current crate
    | impl doesn't use only types from inside the current crate

由于孤儿规则,您不能在外部类型上实现特征。

请参阅在类型上实现特征

但是我们不能在外部类型上实现外部特征。 例如,我们不能在我们的聚合器板条箱中实现 Vec 的 Display trait,因为 Display 和 Vec 都在标准库中定义并且不是我们的聚合器板条箱本地的。 此限制是称为连贯性的属性的一部分,更具体地说是孤儿规则,之所以如此命名是因为父类型不存在。 此规则确保其他人的代码不会破坏您的代码,反之亦然。 如果没有这个规则,两个 crate 可以为相同的类型实现相同的 trait,并且 Rust 不知道使用哪个实现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM