user232343
user232343

Reputation: 2118

Go import modules "later"

Can we have generic importing of modules with go. To be more clear, here is use case:

package main

import (
    "fmt"
    "net/http"
)

json handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "you requested", r.URL.Path)
}

func main() {
    var moduleName String = "/path/to/module"        

    import moduleName
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8000", nil)
}   

So in main you can see that I am trying to import moduleName, but this gives me an error.

Is there some workaround for this?

Upvotes: 1

Views: 374

Answers (2)

Not_a_Golfer
Not_a_Golfer

Reputation: 49177

Go is a statically compiled language, not an interpreted language like Python. Your imports happen in compile time, not in run time. So in short, no, you can only import stuff on the package level.

The official definition makes this clear:

An import declaration states that the source file containing the declaration depends on functionality of the imported package and enables access to exported identifiers of that package.

One more interesting note on imports is that if a package is imported and has an init() function, this function will be called to initialize the package, on program startup; from the docs:

If a package has imports, the imported packages are initialized before initializing the package itself

This leaves some room for dynamic intiailization, but it's far from dynamic imports.

Upvotes: 8

Dekker1
Dekker1

Reputation: 5786

Google Go doesn't natively support dynamic imports. More on this subject can be read here: How to import package by path from string in Go?

In a forum discussion a solution that is suggested is calling the compiler with your specific module. This is however not general practice. The discussion can be found here: https://groups.google.com/forum/#!topic/golang-nuts/Rm0gcBPbxLk

In a general sense I would advise against any such schemes. There are probably different ways to implement the program with the same functionality. If you can't find another scheme for Google Go, try searching for the same kind of schemes in C++, they are usually quite similar.

Upvotes: 1

Related Questions