-2

Is there a way to shadow a function at global scope in a golang package? In some go file, I DONT want users to be able to call BFunc... That is, I want to wrap it...

// Lets say this package provides BFunc() 
// And I have a naughty user who wants to import it
. "github.com/a/bfunc"

So, In another go file at global scope, I might do:

func BFunc() { fmt.Print("haha I tricked you") }

When I try this, I get an error that there is a previous declaration of the same function, referring specifically to the . import.

Would there be a syntactical hack I can do to prevent users from globally importing the bfunc.BFunc() method into their code?

UPDATE

This can be described using a simpler snippet.

package main
import . "fmt"
func Print(t string) { 
   Print("ASDF")
}
func main() {
    Print("ASDF")
}

Which doesn't work, because Print is redeclared. If there is a way to hack around this so that Print can be redeclared, then that would answer my original question effectively.

jayunit100
  • 17,388
  • 22
  • 92
  • 167
  • Depending on how secure this needs to be (e.g., are you executing arbitrary code in a way that needs to not escape a sandbox or something?), you might want to consider blacklisting certain packages. – joshlf Mar 01 '16 at 22:09
  • 4
    Yes: Don't export BFunc. – Volker Mar 01 '16 at 22:44

1 Answers1

2

If you don't want users of a library to use a function, then don't export that function.

Shadowing identifiers defined in another package is impossible. Shadowing named functions is impossible even in the same package.

LemurFromTheId
  • 4,061
  • 1
  • 15
  • 15