首頁 > 後端開發 > Golang > 主體

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

Linda Hamilton
發布: 2024-11-14 22:32:02
原創
334 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板