doudizhu2222 2017-10-19 10:53
浏览 51
已采纳

如何定义静态成员函数?

I'm using golang to build a web server. And I'm using the MVC architecture.

Now I don't know how to make the static member function.

For example, I've a struct User as one of my models:

type User struct{
    name string
    password string
}

Obviously, I need also the functions as below:

func (user User)addUser(){
    conn := ConnToDB()
    query = "insert into user (name, password) values ('" + user.name + "', '" + user.password + "');"
    conn.execute(query)
}
func (user User)changeNameById(id int){
    ...
}

However, I don't know how to make a function to list all names. In Java or Python, such a function should be a static member function of the class User, in this case we can call the function like this:

User.listNames();

How to do the same thing in golang?

  • 写回答

1条回答 默认 最新

  • dongzouban9871 2017-10-19 10:59
    关注

    You simply write a regular function, not a member function:

    func listUserNames() []string {
        ...
    }
    

    When calling it from your package, it will simply be listUserNames()

    When calling it from outside your package, it will be prefixed by your package's name. (Also, you will have to make the function public in order to call it from another package)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序