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
+5.4k Javascript : How to refresh page with JQuery ?
+31.9k Golang : Copy directory - including sub-directories and files
+18.2k Golang : Iterating Elements Over A List
+10k Golang : Wait and sync.WaitGroup example
+8.2k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+10.3k Android Studio : Checkbox for user to select options example
+5k Javascript : Change page title to get viewer attention
+5.5k Cash Flow : 50 days to pay your credit card debt
+6.9k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+40.6k Golang : How to count duplicate items in slice/array?
+26.3k Golang : Encrypt and decrypt data with AES crypto
+15k Golang : Get query string value on a POST request