function - 如何从 Go/Golang 中的另一个方法表达式访问方法表达式(结构函数)?

标签 function go struct model

我正在尝试清理我的 Go/Golang 项目中的代码。我认为以面向对象的方式创建模型可能是惯用的,这样我就可以做到,例如:

  • db.Users.GetID("john")(在“users”表中做一件事)
  • db.Purchases.GetTotal()(在“purchasaes”表中做一件事)

等等。但是,这样做的一个问题是数据库函数无法在需要时自行调用。

这是我正在谈论的一个小的、人为的例子:

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)

请注意,在这个人为设计的示例中,验证用户是否存在毫无意义。然而,重点是数据库函数应该能够调用其他数据库函数,以防有一些实际重要的事情需要验证。

我该如何完成/解决这个问题?

(编辑 - 为清晰起见修改了代码片段。)

最佳答案

您尝试做的事情在 Go 中是不可能的。 Users.Exists 是一个 Method Expression 。有了这些,您就可以采用方法并将其转换为简单的函数类型。

userExists := Users.Exists

user := User{}

// now userExists can be called as a regular function with
// first argument of a Users type
exists := userExists(&user, id)

因此,您无法完全按照上述方式构建模型。

Go 不是一种完全面向对象的语言,您不应该尝试在其中严格复制 OOP 结构和习语。在你上面的例子中,如果你需要一个 Exists 函数,你总是可以将 Users 移到一个单独的包中并将 Exists 定义为一个函数:

package user

type Users struct {}

// other methods on Users type

func Exists(id int) bool {
    // check to see if user exists
}

您现在可以进行以下调用:

import "user"

user.Exists(id)

关于function - 如何从 Go/Golang 中的另一个方法表达式访问方法表达式(结构函数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38518905/

相关文章:

javascript - .each .children() 元素有延迟

c# - 出于可空性分析目的,如何告诉 C# 结构的不可空字段实际上可能为空?

c# - C# 16 字节结构限制是否意味着我不能在结构中使用字符串?

struct - golang 将字节数组转换为结构

C 所有类型参数

javascript - Coffeescript:从同一对象中的函数调用数组函数

javascript - Onclick 元素模拟 Esc 键

time - 在golang中获取3年前的时间戳?

go - 带 gorilla 复用器的速率限制器

go - Go 程序的主 goroutine 和派生 goroutine 之间的区别