Search code examples
oopgostaticmember

How do I define a static member function?


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?


Solution

  • 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)