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
+14.3k Golang : Rename directory
+32.5k Golang : How to check if a date is within certain range?
+48.2k Golang : Upload file from web browser to server
+5.8k Golang : Missing Subversion command
+13.4k Golang : Convert spaces to tabs and back to spaces example
+8.9k Golang : does not implement flag.Value (missing Set method)
+13.1k Golang : Generate Code128 barcode
+10.9k Golang : Intercept and process UNIX signals example
+5.6k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+14.3k Golang : Get URI segments by number and assign as variable example
+7.9k Golang : How To Use Panic and Recover
+8.7k Golang : Go as a script or running go with shebang/hashbang style