How to call function from another file in Go

Go

Go Problem Overview


I want to call function from another file in Go. Can any one help?

test1.go

package main

func main() {
	demo()
}

test2.go

package main

import "fmt"

func main() {
}

func demo() {
	fmt.Println("HI")
}

How to call demo in test2 from test1?

Go Solutions


Solution 1 - Go

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.

Solution 2 - 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.

Solution 3 - Go

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")
}

Solution 4 - Go

A functional, objective, simple quick example:

main.go

package main

import "pathToProject/controllers"

func main() {
	controllers.Test()
}

control.go

package controllers

func Test() {
// Do Something
}

Don't ever forget: Visible External Functions, Variables and Methods starts with Capital Letter.

i.e:

func test() {
    // I am not Visible outside the file
}
 
func Test() {
    // I am VISIBLE OUTSIDE the FILE
}

Solution 5 - Go

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.

Solution 6 - Go

Folder Structure

duplicate | |--duplicate_main.go | |--countLines.go | |--abc.txt

duplicate_main.go

    package main

    import (
	    "fmt"
	    "os"
    )

    func main() {
	    counts := make(map[string]int)
	    files := os.Args[1:]
	    if len(files) == 0 {
		    countLines(os.Stdin, counts)
	    } else {
		    for _, arg := range files {
			    f, err := os.Open(arg)
			    if err != nil {
				    fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
				    continue
			    }
			    countLines(f, counts)
			    f.Close()
		    }
	    }

	    for line, n := range counts {
		    if n > 1 {
			    fmt.Printf("%d\t%s\n", n, line)
		    }
	    }
    }

countLines.go

    package main

    import (
	    "bufio"
	    "os"
    )

    func countLines(f *os.File, counts map[string]int) {
	    input := bufio.NewScanner(f)
	    for input.Scan() {
		    counts[input.Text()]++
	    }
    }
  1. go run ch1_dup2.go countLines.go abc.txt
  2. go run *.go abc.txt
  3. go build ./
  4. go build ch1_dup2.go countLines.go
  5. go build *.go

Solution 7 - Go

You can import functions from another file by declaring the other file as a module. Keep both the files in the same project folder. The first file test1.go should look like this:

package main

func main() {
    demo()
}

From the second file remove the main function because only one main function can exist in a package. The second file, test2.go should look like below:

package main

import "fmt"

func demo() {
    fmt.Println("HI")
}

Now from any terminal with the project directory set as the working directory run the command: go mod init myproject. This would create a file called go.mod in the project directory. The contents of this mod file might look like the below:

module myproject

go 1.16

Now from the terminal simply run the command go run .! The demo function would be executed from the first file as desired !!

Solution 8 - Go

as a stupid person who didn't find out what is going on with go module should say :

  1. create your main.go
  2. in the same directory write this in your terminal

> go mod init "your module name"

  1. create a new directory and go inside it

  2. create a new .go file and write the directory's name as package name

  3. write any function you want ; just notice your function must starts with capital letter

  4. back to main.go and > import "your module name / the name of your new directory"

  5. finally what you need is writing the name of package and your function name after it > "the name of your new dirctory" + . + YourFunction()

  6. and write this in terminal > go run .

you can write go run main.go instead. sometimes you don't want to create a directory and want to create new .go file in the same directory, in this situation you need to be aware of, it doesn't matter to start your function with capital letter or not and you should run all .go files > go run *.go

because > go run main.go

doesn't work.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1788542View Question on Stackoverflow
Solution 1 - GoDenys SéguretView Answer on Stackoverflow
Solution 2 - Gorai.skumarView Answer on Stackoverflow
Solution 3 - GoBill ZelenkoView Answer on Stackoverflow
Solution 4 - GoNicholas Fernandes PaolilloView Answer on Stackoverflow
Solution 5 - Gokiko carisseView Answer on Stackoverflow
Solution 6 - GoSuvodeep DubeyView Answer on Stackoverflow
Solution 7 - GoMGLondonView Answer on Stackoverflow
Solution 8 - GoParsa asadnezhadView Answer on Stackoverflow