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.
以上がGo で外部パッケージから関数を呼び出す方法は?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。