Golang : Call function from another package
Very often new comers learning Go will encounter problem in calling functions from another library or package. Go needs to know the path to the function and you will need to specify this with the import
directive. Also remember that for the function to be exportable(called from other function), the first character must be capital. For example, SayHello
versus sayHello
Typical way of accessing a function is done this way
variable := package.FunctionName()
such as below
Location : (Project/main.go)
package main
import "fmt"
import "Project/myownfunctions" // <-- remember to include the directory/package name - in this case "Project"
func main(){
variable := myownfunctions.SayHello() //<---- function name must be capital!
fmt.Println(variable)
}
and in another file
Location : (Project/myownfunctions/myownfunctions.go)
package myownfunctions
func SayHello() string{
return "Hello from this another package"
}
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+17.2k Golang : Read binary file into memory
+21.2k Golang : Convert Unix timestamp to UTC timestamp
+7.9k Golang : How to use Gorilla webtoolkit context package properly
+17.4k Golang : Check whether a network interface is up on your machine
+5.2k Golang : Process non-XML/JSON formatted ASCII text file example
+9.5k Swift : Convert (cast) String to Integer
+12.9k Golang : Google Drive API upload and rename example
+11.9k Golang : Handle or parse date string with Z suffix(RFC3339) example
+7.8k Yum Error: no such table: packages
+14.8k Golang : Get sub string example
+5.5k Nginx : Password protect a directory/folder