Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call function from another file in go language?

Tags:

go

People also ask

How do you call a function in Golang?

Call() Function in Golang is used to calls the function v with the input arguments in. To access this function, one needs to imports the reflect package in the program. Parameters: This function takes the following parameters: in : This parameter is the []Value type.

How do I use a function from another package?

For example, if we want to use a function called greetings(), then we can't do so if the name of the function is in a smaller case. If we make it Greetings(), then we will be able to access it by putting the name of the package prior to calling the function.


You can't have more than one main in your package.

More generally, you can't have more than one function with a given name in a package.

Remove the main in test2.go and compile the application. The demo function will be visible from test1.go.


Go Lang by default builds/runs only the mentioned file. To Link all files you need to specify the name of all files while running.

Run either of below two commands:

$go run test1.go test2.go. //order of file doesn't matter
$go run *.go

You should do similar thing, if you want to build them.


I was looking for the same thing. To answer your question "How to call demo in test2 from test1?", here is the way I did it. Run this code with go run test1.go command. Change the current_folder to folder where test1.go is.

test1.go

package main

import (
    L "./lib"
)

func main() {
    L.Demo()
}

lib\test2.go

Put test2.go file in subfolder lib

package lib

import "fmt"

// This func must be Exported, Capitalized, and comment added.
func Demo() {
    fmt.Println("HI")
}

If you just run go run test1.go and that file has a reference to a function in another file within the same package, it will error because you didn't tell Go to run the whole package, you told it to only run that one file.

You can tell go to run as a whole package by grouping the files as a package in the run commaned in several ways. Here are some examples (if your terminal is in the directory of your package):

go run ./

OR

go run test1.go test2.go

OR

go run *.go

You can expect the same behavior using the build command, and after running the executable created will run as a grouped package, where the files know about eachothers functions, etc. Example:

go build ./

OR

go build test1.go test2.go

OR

go build *.go

And then afterward simply calling the executable from the command line will give you a similar output to using the run command when you ran all the files together as a whole package. Ex:

./test1

Or whatever your executable filename happens to be called when it was created.