在Go 中呼叫介面指標上的方法
在Go 中,您可能會遇到需要針對介面進行程式設計並使用交易而不修改您的程式碼。一種常見的方法是將指向「物件」的指標傳遞到欄位屬性中,以便在必要時啟用回滾。然而,這種方法可能會導致混亂。
讓我們考慮一個程式碼範例:
package repositories import ( "github.com/coopernurse/gorp" ) type Repository struct { Gorp *gorp.SqlExecutor // Pointer to SqlExecutor } func (r *Repository) GetById(i interface{}, key interface{}) interface{} { obj, err := r.Gorp.Get(i, key) // Call method on pointer if err != nil { panic(err) } return obj }
在這裡,您可能認為需要一個指向 Gorp「物件」的指標來執行回滾。然而,理解 Go 中的一些關鍵概念很重要:
在範例程式碼中,即使您有一個指向 Gorp SqlExecutor 的指針,您也無法呼叫介面指標本身的方法。相反,您正在呼叫基礎值的方法。在這種情況下,底層值是一個 SqlExecutor 結構。
因此,您可以安全地從Repository 結構中刪除指針,只需將SqlExecutor 介面傳遞給Repository:
package repositories import ( "github.com/coopernurse/gorp" ) type Repository struct { Gorp gorp.SqlExecutor // Pointer removed } func (r *Repository) GetById(i interface{}, key interface{}) interface{} { obj, err := r.Gorp.Get(i, key) if err != nil { panic(err) } return obj }
This程式碼將按預期工作,並允許您在不修改底層SqlExecutor 的情況下使用事務。您無需擔心在此上下文中將指標傳遞給介面。
以上是為什麼在 Go 中呼叫方法時應避免使用指向介面值的指標?的詳細內容。更多資訊請關注PHP中文網其他相關文章!