I am from a C background and passing an array in C style causes an error.
package main
import "fmt"
func f(a *int){
fmt.Println(a[1])
}
func main(){
var a [100]int
a[1]=100
f(a)
}
Error:: cannot use a (type [100]int) as type *int in argument to f
As others have mentioned in comments, you probably want to use a slice rather than an array. Slices are passed by reference already, so no need to specify pointers. The make
statement below creates a slice of ints (backed by an array). In the code below, I gave it a length of 2 and a capacity of 100 in order to satisfy your goal of assigning to index 1.
import (
"fmt"
)
func f(a []int) {
fmt.Println(a[1])
}
func main() {
a := make([]int, 2, 100)
a[1] = 100
f(a)
}
you must use a slice instead of an array as argument of function. for example:
func p(a int){
fmt.Println(a)
}
func main() {
var a = make([]int,2,10) //2 is length, 10 is capacity
a[0] = 10
p(a[0])
}
array is value type, slice is reference type. you can see more at https://blog.golang.org/go-slices-usage-and-internals
Wish it help you!