I am new in Golang and I make an example for learning it but I am facing import cycle not allowed into my example so anyone know how to avoid this? Here is my code.
Bank,go
package Bank
import (
"../../class/human"
"fmt"
)
func Transfer(payer, receiver *human.Human, payment float64) {
if payer.Bank > payment {
payer.Bank -= payment
receiver.Bank += payment
} else {
fmt.Println("Bank balance not enough")
}
}
Human.go
package human
// import "../../func/Bank"
type Human struct {
Name string
Cash float64
Bank float64
}
func (h *Human) Transfer(Receiver Human, payment float64) {
}
Main.go
package main
import (
"./class/human"
"./func/Bank"
)
func main() {
gary := human.Human{"Gary", 2000.0, 40000.0}
Sam := human.Human{"Sam", 10000.0, 500000.0}
Bank.Transfer(&Sam, &gary, 5000)
}
In above code is work fine with
Bank.Transfer(&Sam, &gary, 5000)
But I think it should be Human use the Bank function so how can i re-write it into this?
Sam.Transfer(&gary, 5000)
I have tried to import Bank.go in Human.go but got the import cycle not allowed error. I am not sure is that my logical mistake or my bad code design but let see if someone can have a solution on this.
Updated Content below
After reading the message, i still don't understand how to implement Interface in this scenario. However, i did changed my code, please take a look to see if it is much better in code design for golang or it still the same? Thank you.
package main
// Human.go
type Human struct {
Name string
Cash float64
Bank float64
}
// Bank.go
type Bank struct {
Acct *Human
}
func (b *Bank) Transfer(receiver *Human, payment float64) {
payer := b.Acct
payer.Bank -= payment
receiver.Bank += payment
}
// main.go
func main() {
gary := Human{"Gary", 2000.0, 40000.0}
Sam := Human{"Sam", 10000.0, 500000.0}
Sam_Account := Bank{&Sam}
Sam_Account.Transfer(&gary, 5000)
}