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
+9.6k Golang : Play .WAV file from command line
+5.1k Golang : Calculate a pip value and distance to target profit example
+5.7k Swift : Get substring with rangeOfString() function example
+18k Golang : Iterate linked list example
+7.1k Nginx : Password protect a directory/folder
+29.8k Golang : Saving(serializing) and reading file with GOB
+11.2k Golang : Create S3 bucket with official aws-sdk-go package
+30.4k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+20.4k Golang : Reset or rewind io.Reader or io.Writer
+11.2k Golang : Generate random elements without repetition or duplicate
+7.6k Golang : Get YouTube playlist
+14.9k Golang : Reset buffer example