首頁  >  文章  >  後端開發  >  Go中如何呼叫外部包的函數?

Go中如何呼叫外部包的函數?

Linda Hamilton
Linda Hamilton原創
2024-11-14 22:32:02326瀏覽

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.

以上是Go中如何呼叫外部包的函數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn