First of all, the word "variable" might be wrong in the question but I assume the detailed question explains why I'm using the word "variable".
I have two packages with different names but the exact same function(s).
Depending on the input of the user I want to use the function of a package. But instead of switching over the packages I would like to assign the package to a new function with a generic name, how to do this? And if it's not possible, why?
// foo/bar.go
package foo
func Test() {
fmt.Println("hola from bar")
}
// baz/bar.go
package baz
func Test() {
fmt.Println("hola from baz")
}
// main.go
package main
import (
"foo"
"baz"
)
func main() {
thePackage := flag.String("package", "foo", "a package")
if thePackage == "foo" {
howToSetThis := foo // How to do this?
} else {
howToSetThis := baz // How to do this?
}
howToSetThis.Test() // execs Println from one of the two bar.go files
}
In JavaScript I would do something like (simplified):
function foo(){
console.log("hola from foo")
}
function baz(){
console.log("hola from baz")
}
if(somethingInput == "foo"){
var howToSetThis = foo;
} else {
var howToSetThis = baz;
}
howToSetThis();
You could define a interface in a package that requires the functions you want to have in those two packages .
package intfc
type Intfc interface {
Test()
}
And then two structs in different packages which implements that interface
package foo
import "fmt"
type Foo struct {
}
func (f Foo) Test() {
fmt.Println("hola from foo")
}
and
package baz
import "fmt"
type Baz struct {
}
func (f Baz) Test() {
fmt.Println("hola from baz")
}
And then in main do something like this:
package main
import (
"foo"
"baz"
"intfc"
"flag"
)
func main() {
var howToSetThis intfc.Intfc
thePackage := flag.String("package", "foo", "a package")
if *thePackage == "foo" {
howToSetThis = foo.Foo{}
} else {
howToSetThis = baz.Baz{}
}
howToSetThis.Test() // execs Println from one of the two bar.go files
}
At compile time import
is practically if not the first directive to get parsed. That means whatever package name is present in the import directive will be the one used as reference in parsing everything else.
Hence you can't use a dynamic language structure like what you did in Javascript. Cerise's answer is correct.