Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 15491

Why doesn't Rust allow to implement external trait for external struct/enum?

$
0
0

I'd like to use an external trait for multiple libraries that returns vector of structs.

common_lib:
pub struct Post {  pub title: String,}pub enum PostError {  SourceError(String),  Io(String),}#[async_trait]pub trait PostGetter {    async fn get_posts(&self) -> Result<Vec<Post>, PostError>;}

But if I use an external structure for these purposes (which seems logical), then I will not be able to implement (for example) From trait for it. Because both From trait and Post/PostError are external for my library

Try to use common_lib:
use std::io::Error;use some::external::existing::data::strict::PostLike;use common_lib::{Post, PostError};// this code doesn't workimpl From<Error> for PostError {    fn from(value: Error) -> Self {        PostError::Io(value.to_string())    }}// this code also doesn't workimpl From<PostLike> for Post {    fn from(v: PostLike) -> Self {        Post {            title: v.title,        }    }}

What is the right way to do it, from Rust philosophy point of view?


Viewing all articles
Browse latest Browse all 15491

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>