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
+6.6k Golang : Check if password length meet the requirement
+8.7k Golang : Get final balance from bit coin address example
+7.1k Golang : How to fix html/template : "somefile" is undefined error?
+26.6k Golang : Convert file content into array of bytes
+18.1k Golang : Get path name to current directory or folder
+16.1k Golang : How to extract links from web page ?
+10k Golang : Identifying Golang HTTP client request
+12k Golang : Pagination with go-paginator configuration example
+7.1k Golang : Dealing with postal or zip code example
+12.8k Golang : Get terminal width and height example
+4.2k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+6.7k Default cipher that OpenSSL used to encrypt a PEM file