220

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?

1
  • 5
    Don't forget: go run test1.go test2.go Commented May 6, 2022 at 16:32

9 Answers 9

150

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I can build and run after removing main in test2.go but failed to run test1.go using go run test1.go still. Why ?
go run test1.go test2.go
@RichChurcher , you gave the answer. Thanks . Also you should upper case Demo() , public functions are upper cased by convention
If test2 has a struct, will it imported too?
@RaymondChenon Upper case is only required when a function needs to be used in a different package. In this case, since both files are in the same package 'main', they can access 'non-exported' (read private) functions as well. See tour.golang.org/basics/3
|
132

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.

3 Comments

go run *.go clean. That's what I needed
go run . will do.
tnx it's complete above solution
64

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

5 Comments

Make sure the method name is capitalized, otherwise it won't work.
Thank you for your solution, it helped me greatly! :)
Folder structure plays a role here.
If there was a variable named for example "a" in lib\test2.go Demo function, how we could access it in test1.go?
Of course, if lib\test2.go is in a separate folder from the test1.go parent
17

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
}

Comments

12

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 start with capital letter
  4. back to main.go and

import "your_module_name/the_name_of_your_new_directory"

  1. finally what you need is writing the name of package and your function name after it

"the_name_of_your_new_directory" + . + YourFunction()

  1. 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.

1 Comment

Thank you very much, I couldn't figure it out, the missing piece was "your_module_name/..." this was just not intuitive at all and haven't seen it clearly explained.
11

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.

3 Comments

This was the actual solution I was looking for.
Note that go run *.go will not work if you have _test.go files in the package. However go build *.go will work even if you have _test.go files in the package because they're not compiled.
The only answer that should be present in this discussion. 👍
10

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 !!

3 Comments

every time a file is added to a go project, go mod init myproject must be executed (and existing go.mod removed)?
@kev great question! Let me know if you got an answer to it. Really required.
this is the right answer, go mod init ... it's necessary
7
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

Comments

7

Let me try.

Firstly

at the root directory, you can run go mod init mymodule (note: mymodule is just an example name, changes it to what you use)

and maybe you need to run go mod tidy after that.

Folder structure will be like this

.
├── go.mod
├── calculator
│   └── calculator.go
└── main.go

for ./calculator/calculator.go

package calculator

func Sum(a, b int) int {
    return a + b
}

Secondly

you can import calculator package and used function Sum (note that function will have Capitalize naming) in main.go like this

for ./main.go

package main

import (
    "fmt"
    "mymodule/calculator"
)

func main() {
    result := calculator.Sum(1, 2)
    fmt.Println(result)
}

After that

you can run this command at root directory.

go run main.go

Result will return 3 at console.

Bonus: for ./go.mod

module mymodule

go 1.19

ps. This is my first answer ever. I hope this help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.