Reputation: 594
I am confused at when should I pass in my value as a receiver and when should I use the value as a parameter in my function. My main.go file is as shown below:
package main
import "fmt"
type tenNumbers []int
func main() {
arrayOfTen := newArrayOneToTen()
arrayOfTen.print()
}
// not a receiver function because you are not receive anything
func newArrayOneToTen() tenNumbers {
myNumbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
return myNumbers
}
// receiver function because you receive the array
func (t tenNumbers) print() {
for _, value := range t {
if value%2 == 0 {
fmt.Println(value, "even")
} else {
fmt.Println(value, "odd")
}
}
}
If I change my functions to passing in the slice of int as parameters, it still works as shown below. :
package main
import "fmt"
type tenNumbers []int
func main() {
arrayOfTen := newArrayOneToTen()
print(arrayOfTen)
}
// not a receiver function because you are not receive anything
func newArrayOneToTen() tenNumbers {
myNumbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
return myNumbers
}
// receiver function because you receive the array
func print(t tenNumbers) {
for _, value := range t {
if value%2 == 0 {
fmt.Println(value, "even")
} else {
fmt.Println(value, "odd")
}
}
}
Is there a difference between the 2? I am confused as to when I should use receiver or parameter?
Upvotes: 2
Views: 1451
Reputation: 417642
The difference is that in the first case the type tenNumbers
will have a print()
method in its method set, in the second case it won't.
This doesn't matter if you just want to run the function: you may use both solutions.
Use methods if you must implement an interface, and also if the function belongs to the type, this keeps code more organized. See: Functions as the struct fields or as struct methods
Also note that functions cannot be accessed at runtime by name, methods can be. See: Call functions with special prefix/suffix
Another consideration may be regarding generics is that methods can't introduce new type parameters, only "use" type parameters listed at the type definition. Functions can introduce new type parameters. See: How to create generic method in Go? (method must have no type parameters)
Upvotes: 2