Reputation: 365
func printArray(my_arr []int){ // ERROR: cannot use arr (type [8]int) as type []int in argument to printArray
fmt.Println(len(my_arr))
}
func main(){
arr := [...]int{17,-22,15,20,33,25,22,19}
printArray(arr)
}
As in C++ we pass the array in a function using pass by reference. can we do same in GoLang?
Upvotes: 5
Views: 12149
Reputation: 85530
Array elements are passed by values in Go, i.e. the target function gets a copy of the array elements passed. Moreover, []int
refers to a slice of int
and not an array of elements. If you want the traditional C like behaviour, pass the array by its address as printArray(&arr)
and receive it as array *[8]int
.
But even this style isn't idiomatic Go. Use slices instead.
func printArray(arr []int) {
fmt.Printf("%d\n", len(arr))
}
func main() {
arr := []int{17, -22, 15, 20, 33, 25, 22, 19}
printArray(arr)
}
A slice is internally just a pointer to the backing array, so even when its passed by value, any changes to the slice on the receiving function modifies the original backing array and therefore the slice also.
Upvotes: 12
Reputation: 4095
your printArray(my_arr []int)
function's parameter expecting a slice, not an array.
In Go, from syntax [...]{1,2,3}
creating an array with number of elements in the brackets.
NOTE: If you have not any use case specially with an array, please use @inian's answer.
So in this case, there is two ways to do this.
1st way
package main
import "fmt"
func printArray(my_arr []int) {
fmt.Println(len(my_arr))
}
func main() {
arr := [...]int{17, -22, 15, 20, 33, 25, 22, 19}
printArray(arr[:])
}
2nd way
printArray
function.package main
import "fmt"
func printArray(my_arr [8]int) {
fmt.Println(len(my_arr))
}
func main() {
arr := [...]int{17, -22, 15, 20, 33, 25, 22, 19}
printArray(arr)
}
Upvotes: 4