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
+8.9k Golang : Get SPF and DMARC from email headers to fight spam
+6.8k Android Studio : Hello World example
+5.6k Golang : Detect words using using consecutive letters in a given string
+7.3k Linux : How to fix Brother HL-1110 printing blank page problem
+18k Golang : Convert IPv4 address to decimal number(base 10) or integer
+40.3k Golang : Convert to io.ReadSeeker type
+12.4k Golang : "https://" not allowed in import path
+29.3k Golang : JQuery AJAX post data to server and send data back to client example
+7.3k Golang : How to detect if a sentence ends with a punctuation?
+31k Golang : Calculate percentage change of two values
+9.3k Golang : How to protect your source code from client, hosting company or hacker?
+14.5k Golang : Reset buffer example