Is there really no way of getting "Protected" visibility in golang?

Hello all,

I am an experienced programmer, but new to golang. As someone who has produced a lot of code in Java, I come from a heavily object oriented mindset. I think that golang has helped me to code in new ways, and more often than not, I find myself producing more straightforward code, which is good for some reasons. However, one thing that I really miss is the “protected” visibility as we can find in Java.

When I am creating a new go module, I find myself forced to make types and functions public (uppercase initial letter) so that I can do a better job at organizing my code and use functions across packages within the module. I do not want to make them visible to the module users, though.

As an example, if my module has to handle tokens, I want it to have a public function like StoreToken(token string). In another package inside the module I may want to have a function WriteTokenToDB(token string), but I don’t want this function to be visible to the module user, because it is part of the internal architecture of my module and I don’t want outside users to use it, because it makes no sense!

One way of solving it would be to put everything inside the same package, but then the code would be a complete mess…

Any advices?

Never had the issue, but if you really need this maybe just include antoher package and wrap it around all functions you want to export. Just use this export package in other parts of the code.

Just found out that the package name we declare in the file header can be the same across the entire project regardless of nested folders. This might solve the issue for me…

Nope… just changed the package declarations of an entire project, but the fact that I have nested folders with code files led me to the exact same issue…

Why would the code be a complete mess with two functions, both relating to tokens? At any rate, I think you’re looking for internal packages:

You can create reusable packages and export functions that can be imported by your package but nowhere else.

One thing I have seen from people coming from Java is the over creations of packages. Packages in go generally tend to be wide, not narrow like in java.

1 Like

Wow, didn’t know that! Looks like its exactly what I was looking for. Will definitely look into it!

Yes, I see that. I am trying to unleash myself from the Java mindset.