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
+19.2k PHP : Convert(cast) int to double/float
+4.8k Javascript : How to replace HTML inside <div>?
+6.8k Golang : Check from web if Go application is running or not
+18.2k Golang : Archive directory with tar and gzip
+13.6k Golang : Get all local users and print out their home directory, description and group id
+5.7k Mac/Linux/Windows : Get CPU information from command line
+15.1k Golang : Convert slice to array
+18.8k Golang : How to get struct tag and use field name to retrieve data?
+5.5k Golang : Skip or discard items of non-interest when iterating example
+6.4k Golang : Handling Yes No Quit query input
+8.4k Golang : Qt get screen resolution and display on center example