1

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?

user232343
  • 2,008
  • 5
  • 22
  • 34
  • Why would you want to make imports like this? – Michael Banzon May 21 '14 at 14:54
  • 1
    Taking a wild guess, but if you're trying to avoid an import cycle, it might help to have packages implementing HTTP endpoints register themselves from their `init()`s, so you have more flexibility in what imports them. But it heavily depends on how you've laid out your app; here's a somewhat related answer: http://stackoverflow.com/questions/20380333/cyclic-dependencies-and-interfaces-in-golang. If it is a cycle and you need help, post a question like "how do I avoid this cycle?" with details of what imports what and why. – twotwotwo May 21 '14 at 21:15

2 Answers2

8

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.

thwd
  • 23,956
  • 8
  • 74
  • 108
Not_a_Golfer
  • 47,012
  • 14
  • 126
  • 92
1

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.

Community
  • 1
  • 1
Dekker1
  • 5,565
  • 25
  • 33