How to call function from another file in Go

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?


Solution 1:

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

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:

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
}