我正在清理Go/Golang項目中的代碼。我想,這可能是習慣,以創建一個面向對象的方式的模型,這樣我可以做,例如:如何從Go/Golang的另一個方法表達式中訪問方法表達式(結構函數)?
db.Users.GetID("john")
(做的事,在「用戶」表)db.Purchases.GetTotal()
(在「採購」表中做一件事情)
等等。但是,這樣做的一個問題是數據庫函數不能自己調用,如果他們需要的話。
這裏就是我所說的一個微小的,人爲的例子:
package main
import "fmt"
// A model that contains all of the structs for our database tables
type Model struct {
Users
Purchases
}
// A struct for functions that have to do with the "users" table
type Users struct {}
func (self *Users) Exists(id int) bool {
// Check to see if the user exists
// SELECT id FROM users WHERE id = ?
return true // (omitted)
}
// A struct for functions that have to do with the "purchases" table
type Purchases struct {}
func (self *Purchases) Count(id int) int {
// First validate that the user exists
if db.Users.Exists(id) == false { // This fails <--------------
return 0
} else {
// Get the count of that user's purchases
// SELECT COUNT(user_id) FROM purchases WHERE user_id = ?
return 50 // (omitted)
}
}
func main() {
db := Model{}
numPurchases := db.Purchases.Count(123)
if numPurchases != 0 {
fmt.Println("User #123 has", numPurchases, "purchases!")
} else {
fmt.Println("User #123 does not exist!")
}
}
這將導致一個錯誤:
undefined: db in db.Users
如果我改變它只是Users.Exists
代替db.Users.Exists
:
./test.go:22: invalid method expression Users.Exists (needs pointer receiver: (*Users).Exists)
./test.go:22: Users.Exists undefined (type Users has no method Exists)
請注意,在這個人爲的例子中,它是點ss來驗證用戶是否存在。然而,重點在於DB功能應該有能力調用其他DB功能,以防有些事情需要驗證。
我該如何完成/解決此問題?
(編輯 - 修改爲清楚起見,代碼段。)
嗯,我確實設法解決了這個問題,所以我不會那麼快地說這是不可能的。 ;)(看我發佈的答案。) – James
你可以給一個在線工作的例子嗎?你的代碼不能編譯:https://play.golang.org/p/UHmDB39Xxv 另外,說'self.db.Users.Exists(1)'等同於說'user.Exists(id)'在很多更人爲和難以辨認的方式。無論如何,你現在將如何構建一個實際的用戶對象?它現在是不同的類型,導致兩種不同的用戶類型? – abhink
我的歉意。我已經更新了問題代碼和我的回覆代碼,使一切變得更加清晰。它現在也應該編譯。 – James