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?