Home  >  Article  >  Backend Development  >  How Do I Call Functions from Different Packages in Go?

How Do I Call Functions from Different Packages in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-11-20 11:48:05805browse

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:

  • main.go located at MyProj/main.go
  • functions.go located at MyProj/functions/functions.go

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 import path must be an absolute path.
  • You can import packages from external sources by providing the path to the URL with the http or https schema.
  • Avoid using wildcard imports (import _ "package"), as they can lead to dependency issues.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn