0

I'm testing the idea of putting most of my code in an internal package and then picking exactly which of the methods / types from there I'm exposing to the outside world. Code would look like:

/mypackage/internal/catapult

package catapult

func Load(boulder Boulder) {
  // ...
}

func Trigger() *Launch {
  // ...
}

// ...

Maybe Load is being called by other internal packages (/mypackage/internal/randomevents/boredsoldier and /mypackage/internal/actualattackstrategy) but shouldn't be allowed by users outside of internal. All those are allowed to do is Trigger the catapult once it's loaded.

So now I'd like to have a package above internal (/mypackage/general) where Trigger is exposed but not Load. I was hoping to do something like:

package general

const TriggerCatapult = catapult.Trigger
// ^ does not work because a function cannot be a const

var TriggerCatapult = catapult.Trigger
// ^ technically works but now the value of TriggerCatapult can be overwritten by any package user

func TriggerCatapult() *catapult.Launch {
    return catapult.Trigger()
}
// ^ works. It's just "painful" to have to reproduce the entire function's signature every time

Is there a better way to do this?

3
  • 4
    If Trigger is supposed to be public, why define it in an internal package? Commented May 19, 2022 at 17:02
  • I'm struggling to see why you'd use the internal package to ensure things don't "bleed out" outside of the place where you intend to use them, only to jump through hoops to then expose them. The whole point of internal seems a bit moot Commented May 19, 2022 at 19:17
  • 1
    This allows to very selectively decide what you expose. I'm also not saying this is necessarily a great idea. Those are explorations and I don't think explorations and tinkering should be limited to what initially appears like a good or bad way to do something. I'd rather push it as far as I can, see what I actually get and decide then on the value of it. Commented May 20, 2022 at 17:08

1 Answer 1

1

No, there is no better way to do this that the way you provide:

func TriggerCatapult() *catapult.Launch {
    return catapult.Trigger()
}

You shouldn't return unexported types though, and most linters would catch this for you.

If a user is going to interact directly with things in catapult, then that package should not be internal.

Sign up to request clarification or add additional context in comments.

1 Comment

That's the thing, they can interact directly with SOME of the things in that package. And no, it's not about making the things they can't interact with unexported because I'd like to be able to share those with other internal packages.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.