Friday, April 19, 2024
HomeGolangWhen to make use of Sort Embedding? - Getting Assist

When to make use of Sort Embedding? – Getting Assist


For now it happens to me in DTOs generally the necessity to embed sorts (one other DTO) just like the traits.

Should you’re accustomed to different languages that assist inheritance (Java, Python, C++, C#, and so on.). For instance, I’ve a easy TempFile implementation in a few of my packages that’s basically this:

sort TempFile struct {
    *os.File
}

func (f TempFile) Shut() error {
    if err := f.strive("shut", func(f TempFile) error {
        return f.File.Shut()
    }); err != nil {
        return err
    }
    return f.strive("take away", func(f TempFile) error {
        return os.Take away(f.File.Title())
    })
}

func (f TempFile) strive(fn func(TempFile) error) error {
    if err := fn(f); err != nil {
        return fmt.Errorf(
            "error trying to %s file %v: %w",
            what, f.Title(), err,
        )
    }
    return nil
}

So basically, my TempFile sort works the identical as an *os.File, besides when Shut is known as, it calls the “base” *os.File’s Shut perform after which removes the file. If *os.File ever will get a brand new methodology, my TempFile will “inherit” it.

Nonetheless, that is the one scenario that I can consider the place I’ve executed this. Often I find yourself forgetting about embedded capabilities and I by accident do one thing like this:

func (f TempFile) Learn(p []byte) (n int, err error) {
    // ...
    nn, err := self.Learn(p)    // oops, I meant self.File.Learn...
    // ...
}

Which is fairly apparent and but I handle to make the identical mistake greater than as soon as. I assume I’m simply not reduce out for inheritance-like embedding :upside_down_face:

1 Like

That jogged my memory of a line from Bitfield weblog, on this article https://bitfieldconsulting.com/golang/commandments:

Don’t embed struct sorts in order that they magically purchase invisible strategies.

I believe that’s what he’s referring to then. So it could very hardly ever be advisable to embed sorts, until it’s to construct flat structs (with out strategies).

1 Like

Yea, that’s a extremely good level. I’ve executed that particularly with structs with widespread fields that I (un)marshal JSON to/from.

1 Like

This subject was routinely closed 90 days after the final reply. New replies are not allowed.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments