0

Let's us say I have a package which contains different types of TV structs. Now, based on the parameters passed I would like to return a specific TV type.

How is it possible to return the specific type without using the interface type TV in the return type.

Another example, let us say I want to implement different kinds of io.Writer but parallel network writers in a package say network_writers. Do I have just have to have another interface specific for parallel writers to come close to "Accept interfaces, return structs"?

I'm having hard time coming up with a good solution to this problem. While thinking this through I also have a trouble of whether to make this package private or not.

1

This is not a hard rule: we have to use judgement.  The idea is to only abstract the return type when you need to, but sometimes you need to!

Now, based on the parameters passed I would like to return a specific TV type.

I think you'll know when you need to, such the case you're arguing here.

The phrase reminds us to consider calling clients when writing functions, and realize that consuming interfaces as arguments makes the functions/software we're writing more flexible for those calling clients.

For return values, keeping things simple seems appropriate, so no need for an interface unless you have a situation that requires one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.