I have two files main.go
which is under package main
, and another file with some functions in the package called functions.
My question is: How can I call a function from package main
?
File 1: main.go (located in MyProj/main.go)
package main import "fmt" import "functions" // I dont have problem creating the reference here func main(){ c:= functions.getValue() // <---- this is I want to do }
File 2: functions.go (located in MyProj/functions/functions.go)
package functions func getValue() string{ return "Hello from this another package" }
Create a file basic.go inside the basic folder. The file inside the basic folder should start with the line package basic as it belongs to the basic package. Create a file gross.go inside the gross folder. The file inside the gross folder should start with the line package gross as it belongs to the gross package.
You should prefix your import in main.go with: MyProj , because, the directory the code resides in is a package name by default in Go whether you're calling it main or not. It will be named as MyProj . package main just denotes that this file has an executable command which contains func main() .
Go first searches for package directory inside GOROOT/src directory and if it doesn't find the package, then it looks for GOPATH/src . Since, fmt package is part of Go's standard library which is located in GOROOT/src , it is imported from there.
You import the package by its import path, and reference all its exported symbols (those starting with a capital letter) through the package name, like so:
import "MyProj/functions" functions.GetValue()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With