To use traits or to use structs?

Does it make sense to use traits for error types? Or should one use structs? Structs actually feel fairly limiting for various reasons tbh, but it also feels weird to do an read_foo::<MyError>() kinda thing.

I mean, the error type you are using has to be a type, and traits are not types, so you can't really use a trait.

Maybe you can elaborate on how you were thinking of using a trait?

The trait can have functions like fn invalid_syntax(context: ..., problem_element: &str) -> Self;, and then the actual type can inspect the context and grab what it wants from the context. In most cases, only the position is needed, so it could also be a struct Error { position: u64, problem_element: String }, but we're not sure.

also making it a struct would require error wrapping in another part of the code, which arguably isn't that bad but in that part we explicitly do want user-defined error types. so why not make the user implement these too and avoid error wrapping?

It seems like you are assuming a lot of context I don't have.

1 Like

It sounds somewhat similar to the error traits in serde. Here, the file format would define the actual error struct, and the serde internals would use those through a trait.

well, there's no reason the built-in syntax errors should be any more special than user-defined syntax errors, at least. using a trait here would give them equity(?).

I agree with @alice. It's not very clear to me what you're asking. Could you add some code snippets to explain?

so we have this Reader and it comes with some built-in methods like read_integer, but you're also supposed to augment it with your own equivalents of read_* methods, and the built-in methods can return syntax errors.

collecting all these errors into a single error type feels like it just makes the most sense? talking about the issue helped.

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.