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
+11.6k Golang : Simple file scaning and remove virus example
+10.8k Golang : Natural string sorting example
+22k Golang : Match strings by wildcard patterns with filepath.Match() function
+8.2k Golang : Emulate NumPy way of creating matrix example
+12k Golang : Sort and reverse sort a slice of runes
+10.5k Golang : ISO8601 Duration Parser example
+5.6k Golang : Frobnicate or tweaking a string example
+9.9k Golang : Check if user agent is a robot or crawler example
+16.4k Golang : Check if a string contains multiple sub-strings in []string?
+6.8k How to let Facebook Login button redirect to a particular URL ?
+3.6k Java : Get FX sentiment from website example
+6.9k Web : How to see your website from different countries?