144
votes

I want to call function from another file in go lang, 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?

7
What do you mean by go fmt? Like in the terminal or what? How does it show he cares about anything?Charlie Parker

7 Answers

102
votes

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.

78
votes

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.

50
votes

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

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
votes
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
2
votes

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
}
0
votes

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