GO MASTERs! could you advise?
with make([]int,len,cap), does GO allow array initialization at the same time to declaration?
myArray := make([]int, 3, 10){1,2,3}
I see cap(myArray) has changed as same to len(myArray) in the below case. What is fundamental behind?
<ex> myArray := make([]int, 3, 10) myArray = []int{1,2,3} fmt.Println("len:"len(myArray),", cap:",cap(myArray))
len:3, cap:3
Why cap(myArray) is 3 instead of 10 as I declaration?
I initialized individual element directly. And, it works as I wanted
<ex> myArray := make([]int, 3, 10) myArray[0] = 1 myArray[1] = 2 myArray[2] = 3 fmt.Println("len:"len(myArray),", cap:",cap(myArray))
len:3, cap:10
I believe you're getting this result because in the first example you declare a slice with a length of 3 and a cap of 10. However, in the following statement you assign a completely different slice to that variable. Since the slice your assigning was declared/initialized using 'composite-literal' syntax and it has only 3 items, that is the capacity it is initialized with. In your second example, you assign values to each index of the slice you created with make, retaining the length and capacity properties.
To try and give more clarification... In C# or Java or C++ this would be like doing something like this;
List<string> myStrings = new List<string>();
myStrings.Add("A string");
myStrings = new List<string>();
As you might assume, after assigning a new list to the myStrings variable the old list is lost. So to give the simple answer, you're not just overwriting the cap, you're overwriting the whole slice. The value you have in your assignment that overwrites it, causes a slice to be created with a cap of 3 which is why you get that result.
So there's a few things at play here. I would strongly recommend the goblog's explanation of this: https://blog.golang.org/slices (go down to the section labeled Capacity). Also, just a (tiny) bit of semantics, but those are actually slices, not arrays :)
To get to the point, when you first declared your slice, you had a len of 3 and a capacity of 10. No problem with that. But then you redeclare myArray, and set it to be []int{1,2,3}. No problems there either, this is valid.
The problem comes when you expected your previous len/cap to remain the same; your slice is just a pointer to some space in memory. So you've now changed your underlying pointer (see the goblog). The capacity and length of the slice is now changed as well (to the default-- again, see the goblog). You can see the same changing of len/cap if you were to add more elements:
myArray := make([]int, 3, 10)
fmt.Println("len:"len(myArray),", cap:",cap(myArray)) // len: 3 cap: 10
myArray := []int{1, 2, 3}
fmt.Println("len:", len(myArray), "cap:", cap(myArray)) // len: 3 cap: 3
myArray = append(myArray, 4)
fmt.Println("len:", len(myArray), "cap:", cap(myArray)) // len: 4 cap: 8; automatically increases the cap