HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

How to call function from another file in Go

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howfromfunctionfilecallanother

Problem

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

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.

Context

Stack Overflow Q#14155122, score: 150

Revisions (0)

No revisions yet.