5
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?

1
  • 1
    Please take the Tour of Go for language fundamentals like the difference between arrays and slices. Commented May 25, 2021 at 6:27

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So its better to use slice?
@ujjwal_bansal: Yes take the tour of Go - tour.golang.org/moretypes/6 and understand more on the native types
4

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

  • send slice to print from the array
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

  • accept array in printArray function.
  • but this has some limitation, it will accept arrays with the one length. In this case it is 8.
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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.