What is better practice to implement Traits?

I started my studies about Rust recently and I saw some projects doing implementation of Traits in separate files, per example:

a.rs

struct A {
 name: String
}

b.rs

struct B {
  name: String
}

impl From<B> for A {
   fn from(b: B) -> A {
  A {
     name: b.name
  }
}
}

Is it correct?

I had thought that the implementation of From Trait should be in a.rs.

No, there's no such restriction. Within a crate, you are allowed to split implementations across files. Of course the entities involved in the implementation must be visible at the place of the impl.

:thinking:

ok, but that makes the project disorganized, right? because I have some change behaviorals of struct distributed in separate files

Putting impl From<A> for B in either the module of A or the module of B should be fine. Which one you prefer is mostly a philosophical question. Obviously, scattering inherent impls of a simple type across files just because you can is usually not wise, but sometimes it can come in handy.

1 Like

Great, that is my point, thanks for your answers.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.