Search code examples
functionmethodsgo

Whats the difference of functions and methods in Go?


I am trying to get started with Go and the documentation is very good. What I did not find in the documentation is the difference between functions and methods.

As far as I understand at the moment: functions are "global", which means I do not have to import a package to use functions, they are always there. Methods are bound to packages. Is this correct?


Solution

  • As far as I understand at the moment: functions are "global", which means I do not have to import a package to use functions, they are always there. Methods are bound to packages. Is this correct?

    No, that's not correct. There are just a couple of functions from the builtin package which are always available. Everything else needs to be imported.

    The term "method" came up with object-oriented programming. In an OOP language (like C++ for example) you can define a "class" which encapsulates data and functions which belong together. Those functions inside a class are called "methods" and you need an instance of that class to call such a method.

    In Go, the terminology is basically the same, although Go isn't an OOP language in the classical meaning. In Go, a function which takes a receiver is usually called a method (probably just because people are still used to the terminology of OOP).

    So, for example:

    func MyFunction(a, b int) int {
      return a + b
    }
    // Usage:
    // MyFunction(1, 2)
    

    but

    type MyInteger int
    func (a MyInteger) MyMethod(b int) int {
      return a + b
    }
    // Usage:
    // var x MyInteger = 1
    // x.MyMethod(2)