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.2k Golang : Create matrix with Gonum Matrix package example
+5.5k Mac/Linux/Windows : Get CPU information from command line
+7.8k Golang : Scramble and unscramble text message by randomly replacing words
+5.6k Mac OSX : Find large files by size
+9.3k Golang : Bubble sort example
+17.2k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+7.4k Golang : How to get username from email address
+9.2k Golang : Replace a parameter's value inside a configuration file example
+4k Javascript : Change page title to get viewer attention
+4.3k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+10.8k Swift : Convert (cast) Int or int32 value to CGFloat
+3.7k JQuery : Calling a function inside Jquery(document) block