Reputation: 57
if I have the following proj structure:
src/github.com/proj
src/github.com/proj/a
src/github.com/proj/b
and a file in pkg a references a value in pkg b. What should this import look like in the pkg a file?
example: pkg a foo.go
import
(
github.com/proj/b //if this then I would need a go.mod entry
proj/b //no go.mod entry
)
func fooFunc() {
return b.Value
}
Upvotes: 0
Views: 303
Reputation: 15144
Consider the following project structure where .
is your project root folder:
.
├── api
│ └── api.go
├── database
│ └── database.go
├── go.mod
└── main.go
And the source code file contents:
./go.mod
module github.com/myproj
go 1.20
./main.go
package main
import "github.com/myproj/api"
func main() {
api.Create()
}
./api/api.go
package api
import "github.com/myproj/database"
func Create() {
database.Create()
}
./database/database.go
package database
import "fmt"
func Create() {
fmt.Println("OK")
}
Go will automatically interpret your internal packages as dependencies. From the root you run:
go run .
Note that you must make variables and functions public with a upper case first letter in order for external inner packages to have access to it.
func MyPublicFunction(){}
func myPrivateFunction(){}
Upvotes: 0
Reputation: 21
Assuming the following:
Your project is in a single repository on Github (github.com/user/proj), not multiple repositories as implied by the question.
Your project has a single go.mod at the root of the project with module path github.com/user/proj.
The files in directory b use package b
as the package statement.
Use this import:
package a
import (
"github.com/user/proj/b"
)
func fooFunc() {
return b.Value
}
Upvotes: 2