Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

include a secondary file in main go file

Tags:

file

include

go

I have a main.go file that I worked on and now I'm trying to organize since it became a little lengthy. I want to create a new file, put some functions in it and then include it in main.go and use those functions. That new file will be in the same directory as main.go. Anybody have any idea how to do this?

like image 804
Ciprian Turcu Avatar asked Apr 28 '16 03:04

Ciprian Turcu


People also ask

Can a go package have multiple files?

A package can have many files but only one file with main function, since that file will be the entry point of the execution. If a package does not contain a file with main package declaration, then Go creates a package archive ( . a ) file inside pkg directory. Since, app is not an executable package, it created app.


2 Answers

As long as the go files are in the same package, you do not need to import anything.

Example:

project/main.go:

package main

import "fmt"

func main() {
    fmt.Println(sayHello())
}

project/utils.go:

package main

func sayHello() (string) {
    return "hello!"
}

To run: go run main.go utils.go or go run *.go

like image 51
vogtb Avatar answered Oct 03 '22 00:10

vogtb


You don't have to do any including (importing). Just use the same package name in both files.

like image 42
Andy Schweig Avatar answered Oct 03 '22 01:10

Andy Schweig