Answer the question
In order to leave comments, you need to log in
How to work with pointers to arrays (slices) in GO (golang)?
Hey!
I have been studying GO for 2 whole days now, I wrote down a simple program for 200 lines. There is no question of any beauty in it, but "to try" is just right.
I really liked the goroutines (or goroutines or goroutines - there is no one to tell what it is called correctly).
As an obj-si_shnik, I was confused by the lack of arrays with an arbitrary size. (I was also confused by the presence of "slices" - it requires additional investigation) It was decided to write down the append function, which would take an array and what should be stuffed into it under the extra index (oh, generics, generics ...). I would like this function to take not the array itself, but only a pointer to it, but a problem immediately arises: a pointer to an array is received, but len (this_array) is no longer possible to get - len does not accept a pointer. Tell me how to be here?
Maybe I'm digging in the wrong direction? Maybe there are arrays of arbitrary length somewhere in the go-subsoil?
Answer the question
In order to leave comments, you need to log in
I'm about your level in Go, but here's what I imagine: slices are "mutable arrays" for our purposes. In fact, these are references to arrays that are immutable anyway, but if we want to change the size of the slice, then we simply get a new underlying array and a reference to it.
For slices, there is a built-in append function:
s0 := []i n t {0, 0}
s1 := append(s0, 2)
s2 := append(s1, 3, 5, 7)
s3 := append(s2, s0...)
Use slices, this is a reference type. If the size goes beyond the capacity, the slice's internal array will be recreated with a larger capacity.
In principle, you can also look at golang.org/pkg/container
origArray := []string{"1", "2"} //уже дает вам слайс, а не массив
origSlice := origArray[:] //в этой строке нет никакого смысла
//массив можно получить так
var myArray [2]string = [2]string{"1", "2"}
foo(&origSlice){
*origSlice = append(* origSlice, "3")
...
foo (origSlice){
origSlice[1]="baz"
...
}
index0h : I'm not very good at something. Let me try to explain in my own words what you need, and you, if possible, show how this is done in GO.
The first picture shows how you can work with pointers in Swift.
On the 2nd - how I try to do it in GO.
In the console -
[1 2]
[1 2]
if passed as &/* then an error on append
Tell me what's wrong?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question