vendredi 12 février 2021

Run function with known name from package with unknown name

I am creating a program that needs to access other packages functions, I know the function name because it will be standard for every package, what I don't know is the package name.

I would like to be able to include the package in the file but then have something like the following:

import github.com/user/unknownpackagename

...

packageName := "unknownpackagename"

// This is pseudo-code of course. Run is the function
// of which I know the name
(packageName).Run()

Is this in any way possible in Go?

[EDIT] Adding more info hoping to explain it better

I have developed a program that needs to run a function called "Run" from other packages.

I don't know how many packages will be added in the future as their name will be dynamically added to and retrieved from a database.

What I can do right now to solve the problem is the following:

import (
    github.com/user/unknownpackagename
    github.com/user/otherpackagename
)

...

packageName := getPackageName()

switch packageName {
case "unknownpackagename":
    unknownpackage.Run()
case "otherpackagename":
    otherpackagename.Run()
...
}

since there could be hundreds of different packages, I would like to avoid a big big switch statement replacing it with a simpler

"if the package name is this, execute Run() from this package"





Aucun commentaire:

Enregistrer un commentaire