Better wrapper structs
Nobody has claimed this yet.
- Dominant language
- Markdown
- Stars
- 6.6k
- Forks
- 1.7k
- Avg merge
- 16h 14m
- Merged PRs (30d)
- 1
Description
So there isn't inheritance in Rust but you can easily make wrapper structs and implement methods on that. Since this is quite common, there could be a way to avoid needing to always access the extra fields. It's common to use a tuple with one field but normal structs are common too, like String which is a wrapper over a Vec<u8>. I'm not sure how to do this or if it's even needed. If you have your own ideas or you can improve my ideas, feel free to comment.
So my main idea is just a sugar syntax over a tuple with a single field. It would be like the inner type, but with the extra methods from the outer struct. I have 2 ideas how to do this syntax for this idea, using measurements as wrappers over numbers:
- some keyword (
wrapperas a placeholder):
wrapper struct Millimeter(u32);
let mm = Millimeter(21);
- a struct but without fields, only a type:
struct Millimeter u32;
let mm = Millimeter 24;
Which can then be used like this:
impl Millimeter {
fn to_meter(self) {
Meter(self / 1000)
}
}
Millimeter is treated exactly like a u32 but with those extra methods from Millimeter too. So u32 works a little bit like a trait that Millimeter implements and you can pass it to anything that expects a u32 and can also be coerced to a u32:
let mm = ...;
expects_u32(mm);
let num: u32 = mm;
If you don't understand how something might work, I can give more specific examples or you can send me an example and I'll tell you how it would. Or you can send me examples how you think it should work or give an example that demonstrates why it won't work. There could be many situtations where it is very ambiguous.
Is it even worth the effort? I'm trying to learn more about Rust. Understanding what the boundaries are, so explanations why this won't work are appreciated 😁.
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No files, tests, or entry points are named. Start by examining the proposed wrapper syntax, the tuple-struct and String examples, and the stated coercion and method behavior. Done would require a settled design that resolves the noted ambiguities and defines whether the feature is worth pursuing.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100