Improving this small code bit?


I have some simple code below:

fn main() {

// Construct type for particle
struct Particle<T,U,V>{
    pos:  (T, T, T),
    vel:  (U, U, U),
    rhop: V 

// Implement print command for particle
impl<T: std::fmt::Display,U: std::fmt::Display,V: std::fmt::Display> std::fmt::Display for Particle<T,U,V> {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      write!(f, "Position: ({}, {}, {})\nVelocity: ({}, {}, {})\nDensity: {}", self.pos.0, self.pos.1,self.pos.2, self.vel.0,self.vel.1,self.vel.2,self.rhop)

  // Define initial particle
  let position = (5.0,0.0,0.0);
  let velocity = (0.0,0.0,0.0);
  let density  = 1000.0;

  // Set parameters of the particle
  let p = Particle {pos: position, vel: velocity ,rhop: density};
  // Print the particle


I have tried to write it in a way so that it is as generic as possible and can accept different types for different properties. In reality only f32 or f64 would probably be used. I just posted this bit here, curious if anyone would write this differently, and what the advantages would be compared to this.

Kind regards

Overall, it looks reasonable to me. As you add more methods to that structure, you’ll probably want to restrict the type parameters some. For example, you won’t be able to write pos.0 = pos.0 + vel.0 right now: that will require a where T:Add<U, Output=T> clause somewhere.

If you don’t need fine control of the printed form of your structure, you can add a #[derive(Debug)] annotation immediately before struct particle .... That will automatically generate formatting code similar to what you have written that you can use with println!("{:?}",p);. If you decide to keep your Display implementation, consider putting the line use std::fmt::{Display,Formatter}; at the top of the file so that you can use the shorter names.

It’s also usually a good idea to put structure definitions outside of main(). As your code stands now, you won’t be able to write another function that accepts or returns a Particle because it’s only valid inside the body of main.

Thanks. I used your suggestions.

Kind regards

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.