Functions and Methods in Go?
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.
1
type MyInteger int
2
func (a MyInteger) MyMethod(b int) int {
3
return a + b
4
}
5
// Usage:
6
// var x MyInteger = 1
7
// x.MyMethod(2)
Copied!
------
There are two ways of defining them. If you want to modify the receiver use a pointer like:
1
func (s *MyStruct) pointerMethod() { } // method on pointer
Copied!
If you dont need to modify the receiver you can define the receiver as a value like:
1
func (s MyStruct) valueMethod() { } // method on value
Copied!
Last modified 1yr ago
Copy link