Sharing variables between two source files in one package

I am working on a project in Go. For organization, I have code divided into files:

  • server-related functions go to server.go
  • data processing in db.go
  • global variables are in types.go
  • and etc.

I declared the document_root variable in types.go and defined it in main.go with:

 document_root,error := config.GetString("server","document_root") 

In server.go, I have a function to generate an HTTP status code for the requested file, and it does the following:

 _, err := os.Stat(document_root+"/"+filename); 

When compiling, I get this error:

"document_root declared and not used"

What am I doing wrong?

+4
source share
1 answer

I assume in types.go, you declare document_root in the package scope. If so, the problem is this line:

 document_root, error := config.GetString("server", "document_root") 

Here, you inadvertently create another document_root variable local to the main function. You need to write something like this:

 var err error document_root, err = config.GetString("server", "document_root") 
+7
source

Source: https://habr.com/ru/post/1439044/


All Articles