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
+25.2k Golang : Create PDF file from HTML file
+11.4k Golang : Intercept and process UNIX signals example
+9.1k Golang : Go as a script or running go with shebang/hashbang style
+52.8k Golang : How to get struct field and value by name
+37.7k Upload multiple files with Go
+12.8k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+11.7k Golang : Fuzzy string search or approximate string matching example
+14.3k Golang : Convert IP version 6 address to integer or decimal number
+8.3k Golang : Add build version and other information in executables
+6.7k Golang : Totalize or add-up an array or slice example
+23.7k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date