登录
首页 >  Golang >  Go问答

结构体的方法在 Go 中

来源:stackoverflow

时间:2024-03-15 17:45:29 239浏览 收藏

在 Go 中,使用结构体方法可以自定义 ORM 库 gorm 中表的名称。通过实现 tabler 接口,结构体可以指定一个自定义的表名。此接口仅包含一个方法 TableName(),用于返回表名。当 tablename() 为空时,gorm 将从 TableName() 方法和结构体名称中获取表名称。

问题内容

我注意到在 orm 库 gorm 中,您可以使用如下结构定义自定义表名称:

type DeviceStatus struct {
  // Define some Gorm model fields here
}

// TableName custumizes DeviceStatus SQL table name
func (DeviceStatus) TableName() string {
    return "CustomDeviceStatusTableName"
}

这个结构叫什么?我正在尝试通过 google 找到此内容并弄清楚如何进行函数调用。


解决方案


对,它实现了接口,如果 tablename() 为空,gorm 将从 tablename() 方法和结构名称中获取表名称。

您正在实现 tabler 接口。它只包含一个方法:

type tabler interface {
    TableName() string
}

在规格中了解有关 Interface types 的更多信息。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>