Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add construction methods to the duration enum #57

Closed

Conversation

HenningCode
Copy link

Hello @hoodie,

I just created some constructor methods and methods to chain the operations, but its not that elegant, because I had to return a result. Do you have a better idea or would you just remove them again?

@hoodie
Copy link
Collaborator

hoodie commented May 4, 2024

You can probably introduce an intermediate type and only convert to the Duration at the very end. This is something that you find in a bunch of builder pattern implementations.

@HenningCode
Copy link
Author

@hoodie Do you maybe have an example of that? I am a bit new to Rust and havent worked a lot with enum variants.

@hoodie
Copy link
Collaborator

hoodie commented May 4, 2024

Take a look here. Maybe like this

impl Duration {
  fn build() -> DurationBuilder {}
}

and then that DurationBuilder only has the methods and it contains a prototype of the Duration, could even be Duration itself. You could make DurationBuilder::weeks() return the Duration, that would finalize the build.

@HenningCode
Copy link
Author

HenningCode commented May 4, 2024

Ok I understood that now and how it would be implemented in Rust, but thats quite hard / impossible to realize with an enum variant I think.

If you think about this function which would be part of the Durationbuilder: fn year(&mut self, year: u32) -> &mut Self Its not possible to return a &mut Self because you would have to match self and extract and reconstruct a new Durationbuilder. Also there is nothing that stops you from calling .year(2) on the Weeks variant type. One solution would be to create two seperate structs for Weeks and YMDHMS, which would require a big rewrite..

@HenningCode
Copy link
Author

Closing this for the same reason as this.

@HenningCode HenningCode closed this May 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants