Reputation: 517
Go noob, I cannot seem to figure out how to structure my project with packages. What I want is this:
dart.go
package main
import (
...
)
func main () {
...
// call functions declared in functions.go
...
}
functions.go
package dart
import (
...
)
func Function1() {
...
}
func Function2() {
...
}
Upvotes: 17
Views: 29039
Reputation: 187
As Wombologist mentioned, you can split different files under the same package without problem, assuming they share the same package
definition. The only exception for different package definitions under the same directory is for tests, where the recommended way of defining the package is adding _test
on it (e.g. package main_test
or package dart_test
).
Not sure if it's your case here or if you are just experimenting with the language, but I would add that Go projects are easier to maintain when you group same domain code under packages and share them around, increasing the potential reusability.
Upvotes: 4
Reputation: 1162
If you are just looking to create a library then you won't need a main package. However, if you are looking to create a standalone program that runs functions from a different package (dartlib
) then you'll need a main file.
It would also be a good idea to name your program something different than the library you are calling (program dart
calling library dartlib
)
Library
Your library directory structure should look something like the following:
dartlib
|
dartlib.go
dartlib.go
package dartlib
function Hello() string { return "hello!" }
This can be imported as the following:
"github.com/your_github_username/dartlib"
Program
Or, you can store the package within your program directory. In this case the directory structure should look something like the following:
dart (you_program_name)
|
dart.go
dartlib (package)
|
dartlib.go
In this case, the library can be imported as the following:
"github.com/your_github_username/dart/dartlib"
dart.go
package main
import (
"github.com/your_github_username/dart/dartlib"
"fmt"
)
helloString := dartlib.Hello()
fmt.Println(helloString)
go build .
at directory root produces the dart
executable.
$./dart
hello!
For more examples and further explanation see the docs
Upvotes: 4
Reputation: 546
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.
Upvotes: 23