Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function from another package in Go

Tags:

go

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" } 
like image 405
CABascourt Avatar asked Oct 01 '14 13:10

CABascourt


People also ask

How do you call a function from another package in Golang?

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.

How do I use a function from another 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() .

How can you tell go to import a package from a different location?

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.


1 Answers

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() 
like image 106
JimB Avatar answered Sep 22 '22 13:09

JimB