Solved: Call function from another package in GO


Written by - Deepak Prasad

How to call function from another package in golang

In golang we create multiple packages which contains functions in individual packages. Now we may have a requirement to access these function across packages in such case follow the below mentioned important points:

  • Import the package which contains the function you plan to use
  • The function to be used in another package must start with a capital letter i.e func Fullname(element,element2 string) string{} , so that it will be public outside its package. Once defined using the lower case syntax i.e func fullName()string{} its only accessible with thin that package.
  • You can refer the function using the package name. For example if your package name is greeting and the function name is HelloWorld then you have to import greeting and execute the function using greeting.HelloWorld()

Let us check this using some examples:

 

Overview of a Function in Go

In Golang, all standard libraries are written using functions. i.e json.Marshal() function from encoding/json package which is used to encode string of values into json format. Also, we have fmt package which helps use to format and print output on a terminal, i.e fmt.Println and fmt.Printf()functions.

In a nutshell, Function represents the largest part of a program. It's defined once but can be reused across the whole program. It always only solves a specific problem within the program. i.e fmt.Errorf() function to customize error output.

I have already written a detailed article explaining different areas of using golang function with practical examples.

 

Example to access function from another package

We will create a simple project that takes in a combination of numeric and alphabets but it should only return the most frequent alphabet only.

Step-1: Create and initialize project module

$ mkdir golinuxcloud   
$ cd golinuxcloud 
$ go mod init golinuxcloud
$ touch main.go

For more information about modules read this article modules read this article

 

Step-2: Create custom package with some functions

Let create another directory.

$ mkdir methods 
$ touch methods.go
// methods directory
package methods

import (
	"fmt"
	"regexp"
	"sort"
)
type data struct {
	key   string
	value int
}

// Notice the function name starts with CAPITAL Letter
func AlphabetsOnly(str string) string {
	// accepted A-Z and a-z
	match := regexp.MustCompile(`[^a-zA-Z]+`)
	// map of key:value
	maxVal := make(map[string]int)
	for i := 0; i  results[j].value
	})

        // initialize struct
	results:= []data{}

	// loop through map of strings and append key and values to struct
	for key, val := range maxVal {
		results = append(results, data{key: key, value: val})
	}

	// sort data in the struct
	sort.Slice(results, func(i, j int) bool {
		return results[i].value > results[j].value
	})
        // format outputs
	fmt.Printf("All Elements are: %v \t \n", results)
	var i = 0
	for i < len(results) {
		return fmt.Sprintf("Most frequent character is %s", results[i].key)
	}
        // return values
	return ""
}

Explanation:-

We have imported all necessary packages, fmt for formatting output, regexp for defining a particular pattern and sort for arranging output in ascending order.
AlphabetsOnly(str string)string{} function that accepts string inputs and returns a string. match variable is used to hold pattern to only allow alphabets only not numbers. maxVal holds a map of key and value of type string and integer. i.e p:2 meaning p as occurred twice in that string. we loop through the passed match values and if it exists in maxVal we increment else we create a new element. we have a data struct to hold keys and values for easy sorting. we can sort the elements in a struct and print only the highest occurring character.

 

Step-3: Execute function in main from custom package

In the main package. we have imported our custom package i.e. golinuxcloud/methods as "t" so now we can use to to execute the functions from methods package. Later we are calling t.AlphabetsOnly function from methods package.

// root of the project

// main.go
package main

import (
	t "golinuxcloud/methods"
	"fmt"
	"os"
)

func main() {
	fmt.Println("Kindly provide a string of mixed numeric and alphabets such as zAAz1AAAA234aacjdcc ")
	stringElements := os.Args[1]

	// call go function AlphabetsOnly from methods package
	result := t.AlphabetsOnly(stringElements)
	fmt.Println(result)

}

Explanation:-

We have imported our function from t "golinuxcloud/methods" where t is an alias to the package. OS package helps in passing arguments on the terminal and finally we can print output using fmt package.

We call the function from method package as result := t.AlphabetsOnly(stringElements). arguments from terminal are read and passed to the function for processing only alphabets and return results are stored into result variable then later printed out.

Output

$ go run main.go rmysyuio0393839ftsy
Kindly provide a string of mixed numeric and alphabets such as zAAz1AAAA234aacjdcc
All Elements are: [{y 3} {s 2} {m 1} {o 1} {f 1} {t 1} {r 1} {u 1} {i 1}]        
Most frequent character is y

Similarly you can call your function from any other package.

 

Summary

Go is a statically typed language and high-level syntax. is functional-based and developers are encouraged to master this pattern. The function forms a great foundation of Golang and it is inherited across the entire programming language. In the article, you have learned how to call a function from another package.

 

References

Call module code
Call a function from another package in Go

 

Related Keywords: golang call function from another directory, call function from same package golang, golang call function from main package, how to call another function in golang, golang import local package, function not declared by package golang

 

Views: 8

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can reach out to him on his LinkedIn profile or join on Facebook page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment