Home > Article > Backend Development > How to Call Functions from an External Package in Go?
Calling Functions from an External Package in Go
When working with modular code in Go, scenarios arise where it becomes necessary to access functions defined in separate packages. This guide will provide a comprehensive solution to calling a function from another package in Go.
In the provided example, we have two files: main.go under the main package and functions.go under a package called functions. The goal is to access the getValue() function from the functions package in the main function within main.go.
Importing the Package
To access a function from another package, you must first import the package into your own code. This is done by adding an import statement at the beginning of your code file:
import "MyProj/functions"
Replace MyProj with the actual import path of the package containing the function you want to call.
Calling the Function
Once you've imported the package, you can reference the exported symbols (functions or variables) by using the package name followed by a dot and the symbol name:
functions.GetValue()
In this case, GetValue() is an exported function in the functions package.
Note: Exported symbols in Go start with a capital letter, while unexported symbols start with a lowercase letter.
Complete Code:
Here's the updated main.go file with the necessary changes:
package main import ( "fmt" "MyProj/functions" ) func main() { returnedValue := functions.GetValue() fmt.Println(returnedValue) }
This code imports the functions package and calls the GetValue() function to print its return value to the console.
The above is the detailed content of How to Call Functions from an External Package in Go?. For more information, please follow other related articles on the PHP Chinese website!