Shadowing a global function - go

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.

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.

Related

Inheritance in golang

I'm trying to create a template method that should be executed a certain other method is called.
For example:
func main(){
onInit()
}
func onInit(){
var Instance entity.EntityInstance
Instance.Init()
//do something
}
Another source file, instance.go
type EntityInstance struct{
name string
version string
}
func (instance *EntityInstance) Init(){
// do some initialization
}
The main method is in different code base/app and uses the Instance app to invoke certain initializations.
Currently the user writing this above main method needs to explicitly call the Instance.init()
The objective is for the developers (in this case one who implements the main method) only concern themselves with any of their custom initializations and not worry about calling "Instance.Init()". The OnInit() invoke should take care of "Instance.Init()" implicitly.
Any help to get me started in the right direction ?
EDIT: I do understand that the exact OOP concepts cannot be translated here in Golang but all I'm looking for is the appropriate approach. Clearly, I need to change the way I think of design in here but just don't know how.
Your question is a little unclear, I suspect because you are trying to directly translate ideas and idioms from another language, you should resist doing that. However, if you want an implicit init for a package in Go, you can use the magic function name
func init(){}
https://golang.org/doc/effective_go.html#init
Finally, each source file can define its own niladic init function to
set up whatever state is required. (Actually each file can have
multiple init functions.) And finally means finally: init is called
after all the variable declarations in the package have evaluated
their initializers, and those are evaluated only after all the
imported packages have been initialized.
Be careful with this though, it is implicit behaviour and could cause mysterious bugs if your callers don't know it is happening when they import your package.

What's the purpose of golang allowing multiple init in one package?

I know that golang allows multiple init in one package and even in one file.
I am wondering why?
For example, if a pkg has many files, we could write multiple init then we could get lost in where to we should put init, and we could be also confused about the init order if we have multiple init in one pkg. (I mean is this better? we can only have 1 init, then we can have some initXXX, then put them into init, it seems quite clean.)
What's the advantage of doing this in code struct view?
This question may be somewhat opinion based, but using multiple package init() functions can make your code easier to read and maintain.
If your source files are large, usually you arrange their content (e.g. types, variable declarations, methods etc.) in some logical order. Allowance of multiple init() functions gives you the possibility to put initialization code near to the parts they ought to initialize. If this would not be allowed, you would be forced to use a single init() function per package, and put everything in it, far from the variables they need to initialize.
Yes, having multiple init() functions may require some care regarding the execution order, but know that using multiple init() functions is not a requirement, it's just a possibility. And you can write init() functions to not have "side" effects, to not rely on the completion of other init() functions.
If that is unavoidable, you can create one "master" init() which explicitly controls the order of other, "child" init() functions.
An example of a "master" init() controlling other initialization functions:
func init() {
initA()
initB()
}
func initA() {}
func initB() {}
In the above example, initA() will always run before initB().
Relevant section from spec: Package initialization.
Also see related question: What does lexical file name order mean?
Another use case for multiple init() functions is adding functionality based on build tags. The init() function can be used to add hooks into the existing package and extend its functionality.
The following is a condensed example demonstrating the addition of more commands to a CLI utility based on build tags.
package main
import "github.com/spf13/cobra"
var rootCmd = &cobra.Command{Use: "foo", Short: "foo"}
func init() {
rootCmd.AddCommand(
&cobra.Command{Use: "CMD1", Short: "Command1"},
&cobra.Command{Use: "CMD2", Short: "Command2"},
)
}
func main() {
rootCmd.Execute()
}
The above is the "vanilla" version of the utility.
// +build debugcommands
package main
import "github.com/spf13/cobra"
func init() {
rootCmd.AddCommand(&cobra.Command{Use: "DEBUG-CMD1", Short: "Debug command1"})
}
The contents of the second file extends the standard command with additional commands that are mostly relevant during development.
Compiling using go build -tags debugcommands will produce a binary with the added commands, while omitting the -tags flag will produce a standard version.

Getting list of exported functions from a package in golang

Let's say I have some package
// ./somepkg/someFile.go
package somepkg
import "fmt"
func AnExportedFunc(someArg string) {
fmt.Println("Hello world!")
fmt.Println(someArg)
)
and I import it from my main go file
// ./main.go
package main
import (
"./somepkg" // Let's just pretend I have the full path written out
"fmt"
)
func main() {
fmt.Println("I want to get a list of exported funcs from package 'somefolder'")
}
Is there a way to get access to the exported functions from package 'somepkg' and then to consequently call them? Argument numbers/types would be consistent across all functions in somepkg. I've looked through the reflection package but I'm not sure if I can get the list and call the functions without knowing any information other than package name. I may be missing something from the godocs however, so any advice is appreciated. What I'm trying to do is essentially have a system where people can drop in .go files as a sort of "plugin". These "plugins" will have a single exported function which the main program itself will call with a consistent number and types of args. Access to this codebase is restricted so there are no security concerns with arbitrary code execution by contributors.
Note: This is all compiled so there are no runtime restrictions
What I'm trying to do is something like this if written in python
# test.py
def abc():
print "I'm abc"
def cba():
print "I'm cba"
and
# foo.py
import test
flist = filter(lambda fname: fname[0] != "_", dir(test))
# Let's forget for a moment how eval() is terrible
for fname in flist:
eval("test."+fname+"()")
running foo.py returns
I'm abc
I'm cba
Is this possible in golang?
Edit:
I should note that I have already "accomplished" this with something very similar to http://mikespook.com/2012/07/function-call-by-name-in-golang/ but require that each additional "plugin" add its exported function to a package global map. While this "works", this feels hacky (as if this whole program isn't... lol;) and would prefer if I could do it without requiring any additional work from the plugin writers. Basically I want to make it as "drop and go" as possible.
As you might've guessed, it is difficult to achieve in Go, if not impossible, as Go is a compiled-language.
Traversing a package for exported functions can only get you the list of functions. A sample for this is: Playground. This is a AST (Abstract Syntax Tree) method which means calling the functions dynamically is not possible, or requires too much of workarounds. Parsing function name string as function type doesn't work here.
Alternatively, you can use try methods by binding the exported functions to some type.
type Task struct {}
func (Task) Process0()
func (Task) Process1(v int)
func (Task) Process2(v float64)
func (Task) Process3(v1 bool, v2 string)
This totally changes the way we operate as the 4 methods are now associated with a type Task and we can pass empty instance of Task to call the methods defined on it. This might look like just another workaround, but is very common in languages like Go. A sample for this in Playground which actually works as expected.
In both the examples, I've used multiple files in playground. If you are not familiar with this structure, just create your workspace in your local as following and copy the code under each file name from playground:
<Your project>
├── go.mod
├── main.go
└── task
└── task.go
References:
How to dynamically call all methods of a struct in Golang? [duplicate]
How to inspect function arguments and types [duplicate]
How do I list the public methods of a package in golang [duplicate]
Abstract Syntax Tree - Wiki
Functions vs Methods in Go
The easiest way to do this is to use the template library to parse your code and insert the new package name where appropriate.
Playground
You can use this by loading all of the finals where you call the user package and then output the generated file to the execution directory.

How to define a struct globally and reuse it packages

Im very new to Go and have this "design" problem.
I have a main program passing jobs through channels. Each job will end up in a function defined in separate "worker" packages. Jobs are structs.
Now i want each function called, to return result as a common struct through a "result" channel. But the package doesnt know about the struct definition i have in main and so i cannot define it.
package main
type resultEvent struct {
name string
desc string
}
Then in a worker package:
package worker
func Test() {
result := &resultEvent{name: "test"}
}
Of course the idea is to eventually send this result down a channel, but even this simple example wont work, because worker doesnt know about resultEvent.
What would be the correct way of doing this?
Update:
It should be noted that there will be many worker packages, doing different things. Sorta like "plugins" (only not pluggable at all).
I dont want to define a redundant struct in each go-file and then have to maintain that over maybe 50 very different worker-packages.
Im looking for what would be the correct way to structure this, so i can reuse one struct for all worker-packages.
Basically, anything that lives in package main will only ever be able to be referenced from that pacakge. If you want it to be shared between multiple packages, put it in the worker package and export it (Upper case the first letter), then import worker from main.
No matter what, you will have to import the package which contains the type you'd like to use. However, the reason this isn't working for you is because your type is not exported. You need to uppercase the types name like;
type ResultEvent struct {
name string
desc string
}
Worth checking out what exported vs unexported means but basically upper case means exported which is similar to the public specifier in other systems languages. Lower case means unexported which is more like internal or private.
As pointed out in the comment and other answer you can't import main so I believe you'll have to move your types definition as well.
One possible way would be something like:
package workerlib
type ResultEvent struct {
Name string // Export the struct fields, unless you have a
Description string // real good reason not to.
}
Then stick the rest of the worker utility functions in that package. Unless you provide suitable methods to read the name and description from an event, simply export the fields. If you have an absolute need to make them changeable only from within the package they're defined in, you could keep them unexported, then provide a function to create a ResultEvent as well as methods to read the name and description.

What does an underscore in front of an import statement mean?

In this code from go-sqlite3:
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
"log"
"os"
)
what does the underscore in the import statement mean?
It's for importing a package solely for its side-effects.
From the Go Specification:
To import a package solely for its side-effects (initialization), use the blank identifier as explicit package name:
import _ "lib/math"
In sqlite3
In the case of go-sqlite3, the underscore import is used for the side-effect of registering the sqlite3 driver as a database driver in the init() function, without importing any other functions:
sql.Register("sqlite3", &SQLiteDriver{})
Once it's registered in this way, sqlite3 can be used with the standard library's sql interface in your code like in the example:
db, err := sql.Open("sqlite3", "./foo.db")
While other answers described it completely, for "Show me The Code" people, this basically means: create package-level variables and execute the init function of that package.
And (if any) the hierarchy of package-level variables & init functions of packages that, this package has imported.
The only side effect that a package can make, without being actually called, is by creating package-level variables (public or private) and inside it's init function.
Note: There is a trick to run a function before even init function. We can use package-level variables for this by initializing them using that function.
func theVeryFirstFunction() int {
log.Println("theVeryFirstFunction")
return 6
}
var (
Num = theVeryFirstFunction()
)
func init() { log.Println("init", Num) }
https://golang.org/doc/effective_go.html#blank
It's either a work in progress, or imported for side effects. In this case, I believe it's for the side effects, as described in the doc.
Let's say you have an Animal package. And your main file wants to use that Animal package to call a method called Speak but there are many different types of animals and each animal implemented their own common Talk method. So let's say you want to call a method Speak implemented in the Animal's package which internally calls Talk method implemented in each of the animal's package. So in this case you just want to do an import _ "dog" which will actually call the init method defined inside the dog package which actually registers a Talk method with the Animal package which it too imports.
As I'm new in Go, this definition made it more clear:
Underscore is a special character in Go which acts as null container. Since we are importing a package but not using it, Go compiler will complain about it. To avoid that, we are storing reference of that package into _ and Go compiler will simply ignore it.
Aliasing a package with an underscore which seems to do nothing is quite useful sometimes when you want to initialize a package but not use it.
Link

Resources