Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go package with multiple files, how to structure

Tags:

package

go

Go noob, I cannot seem to figure out how to structure my project with packages. What I want is this:

  • I want to create a package, lets say its called Dart.
  • I have a file called dart.go with package main and the main function in my project directory.
  • I have another file, lets call it functions.go in my project directory with 'package dart' as the first line.
  • I just want to call functions from functions.go in main, but cannot figure out how to name the packages to get it to build.
  • If I put package dart at the top of functions.go it wont build because it finds packages main and dart. I dont want functions.go to be part of another package, I just want one package and the ability to split the functions in this package into multiple files.
  • Is this possible in go, or do I have to make multiple packages?

dart.go

package main 

import (
  ...
)  

func main () {
  ...
  // call functions declared in functions.go
  ...
}

functions.go

package dart  

import (
  ...
)

func Function1() {
  ... 
}

func Function2() {
  ...
}
like image 374
bitwitch Avatar asked May 21 '19 18:05

bitwitch


People also ask

Can a Go package have multiple files?

A package is a file or a group of files with a namespace and some code or related code. This means that a package could live in a file such as math.go or across multiple files such as add.go , subctract.go , multiply.go , this would many files or the singular file will be namespaced as package math for example.

How do I run a Go program with multiple files?

If you are trying to run multiple files on localhost using gorilla mux in go as per latest version(1.11). Try using any of the following 2 commands. go install && FolderName -port 8081 . go build && ./FolderName -port 8081.

What is the difference between Go module and package?

In Go, a package is a directory of .go files, and packages form the basic building blocks of a Go program. Using packages, you organize your code into reusable units. A module, on the other hand, is a collection of Go packages, with dependencies and versioning built-in.


1 Answers

if all you want to do is access functions in a different file, have functions.go also start with package main instead of package dart. That way, you are working within a single package but with your code divided into multiple files. Make sure they're in the same directory so that they're considered in the same package.

like image 180
Wombologist Avatar answered Oct 05 '22 12:10

Wombologist