简体   繁体   中英

Error while using TryFrom for String in Rust

I am trying to implement TryFrom for converting a string to a slice with the help of the following code shown below.

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)
    }
}

I am getting a compilation error when I call

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

You are not allowed to implement traits on external types because of the orphan rule.

See Implementing a Trait on a Type :

But we can't implement external traits on external types. For example, we can't implement the Display trait on Vec within our aggregator crate, because Display and Vec are both defined in the standard library and aren't local to our aggregator crate. This restriction is part of a property called coherence, and more specifically the orphan rule, so named because the parent type is not present. This rule ensures that other people's code can't break your code and vice versa. Without the rule, two crates could implement the same trait for the same type, and Rust wouldn't know which implementation to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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