I'm going to modularize my project, but I have some problems.
Normally, I will put all model files into the same package models (same folder, about 30 files), but now I want to put them into separate folders to manage them easier (each module will have their own model folder).
But if I try to put the model in separate folders like in this image, I will get "import cycle error" because they are not the same package (two tables will be used to lookup each other, this is where error happens).
https://i.imgur.com/3wqJ4BK.png
So is there anyway to put models in separate folders or better ways to manage models?
I'm not sure that this is a good strategy or not. But If I were in your situation I would try to solve it by following approach.
Let's consider we have two packages package a
and package b
.
package a
import ".../code/module2"
var StrA="Hi! I'm A and I'm calling B: "
func FuncA() string {
return "Inside A"
}
func AtoB() {
fmt.Println(StrA+b.FuncB())
}
package b
import ".../code/module1"
var StrB="Hi! I'm B and I'm calling A: "
func FuncB() string {
return "Inside B"
}
func BtoA() {
fmt.Println(StrB+a.FuncA())
}
You cannot use function AtoB()
or BtoA()
because it will make a loop. One possible way you can solve it by making sub-directory inside each module. Move those part of the code that makes loop. Like here AtoB()
and BtoA()
.
Inside extraA.go
:
package extended
import (
"fmt"
. ".../code/module1"
b ".../code/module2"
)
func AtoB() {
fmt.Println(StrA+b.FuncB())
}
I imported package a
using .
so that I can use a
's object locally and imported package b
to call FuncB()
. I also move the BtoA()
to another sub-directory inside module2
.
Now I can use both function without making any loop.
package main
import (
extraA ".../code/module1/extended"
extraB ".../code/module2/extended"
)
func main() {
extraA.AtoB()
extraB.BtoA()
}
Output:
Hi! I'm A and I'm calling B: Inside B
Hi! I'm B and I'm calling A: Inside A