Home > Article > Backend Development > How Do I Call Functions from Different Packages in Go?
Calling Functions from Different Packages in Go
In Go, you may have multiple packages within a single project. This allows you to organize your code and segregate reusable functions and modules. Sometimes, you may need to call a function defined in another package from a different package. This can be done with the help of the import statement.
Importing the Package
To call a function from a different package, you first need to import that package into your current package. This is done using the import statement. The import path is the absolute path to the package, starting from your project root.
For example, let's say you have two files:
To call a function from the functions package in main.go, you would import the functions package using the following import statement:
import "MyProj/functions"
This creates a reference to the functions package in your main package.
Calling the Function
Once you have imported the package, you can call its exported functions directly. Exported functions are those that start with a capital letter. To call a function, simply use the package name followed by the function name.
For example, if you have the following function in your functions.go file:
package functions func GetValue() string { return "Hello from this another package" }
You can call this function from your main.go file by using the following syntax:
package main import "fmt" import "MyProj/functions" func main() { c := functions.GetValue() // Calling the GetValue function fmt.Println(c) }
Additional Notes
The above is the detailed content of How Do I Call Functions from Different Packages in Go?. For more information, please follow other related articles on the PHP Chinese website!