How to use functions from another package in Golang?


We know that every code in Golang is present inside a package, which can either be an executable one or a utility one. The executable package name is usually main and the name of the utility package can be anything, in most cases, it is the name of the folder.

Suppose we have a directory structure that looks something like this.

.
|-- greet
|    `-- greet.go
|-- sample
|    `-- sample.go

We have two directories, namely, greet and sample, and each of them contains a single .go file inside them. Now, we want to make use of a function that is present inside the greet directory.

The first step to access any particular function from a different package is to check whether the function is actually exported or not, and for that, we just need to make sure that the name of the function is Capitalized or not.

For example, if we want to use a function called greetings(), then we can't do so if the name of the function is in a smaller case. If we make it Greetings(), then we will be able to access it by putting the name of the package prior to calling the function.

The next step is to import the package in the code in which we want to use it. We can import the package inside the import statement in our Go program, just make sure you write the entire name after the GOPATH variable matches.

Now, let's check the code inside the greet.go file.

Example 1

Consider the code shown below.

package greet

import "fmt"

// Greeting ...
func Greeting() {
   fmt.Println("Welcome to TutorialsPoint!")
}

The next step is to use the Greeting() function of the greet package inside the sample.go file.

Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

Welcome to TutorialsPoint!

Example 2

Consider the code shown below.

package main

import (
   greet "data-structures/recursion/greet"
   "fmt"
)

func main() {
   fmt.Println("Inside main")
   greet.Greeting()
}

Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

Inside main
Welcome to TutorialsPoint!

Updated on: 21-Feb-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements