Henry Thanks for your time, You're right. Sounds reasonable. But you know, the first time I saw this thing, I was like, when I pass the new slice to my existing slice, does it not replace the item in the same address in memory that my slice has before? Because when I pass new data to my variable, it means I didn't need that data anymore. I need the new data, so when the length of array/slice is the same, Golang has not pasted the data into the same address in memory that my variable has before. It just changed the variable's pointer to a new address that "append" created in the memory.
On Sunday, August 8, 2021 at 8:25:23 PM UTC+4:30 Henry wrote: > Append is for appending items at the end of a slice. If there is enough > space, Go will simply append the items and return the slice. If there is > not enough space, Go will create a new slice with double the capacity of > the existing slice or at least enough space to hold the new items > (whichever is larger), copy the items, and return the new slice. > > In your case, when you first instantiate the slice, Go allocates just > enough memory to hold the numbers. Then, in your append, Go checks whether > "nums[len(nums) - k:]" has enough remaining capacity to hold the new items. > Note that "nums[len(nums) - k:]" is a new slice and it has a shorter > capacity than the original slice. Since there is not enough space, Go > creates a new slice, copy the items, and returns the new slice. That is how > you got the new slice. > > If what you need is rotation, you may want to rotate the items manually. > > On Saturday, August 7, 2021 at 12:00:35 AM UTC+7 Konstantin Khomoutov > wrote: > >> On Fri, Aug 06, 2021 at 12:42:34AM -0700, Miraddo wrote: >> >> Hi! >> >> > I can not understand why when we use append, it does not rewrite values >> in >> > the same address in the memory that it had before, >> > >> > (I'm not sure it "append" problem or the variable | or just my problem >> for >> > sure :) ) >> [...] >> > I saw all addresses in memory was changed, >> > >> > now my question is why it doesn't rewrite the values in the same >> address as >> > before? >> [...] >> >> Have you read and understood [1] and [2]? >> I think the information from these articles will enable you to solve your >> problem all by yourself. >> >> I would also argue that rotating an array *in place* by a non-negative >> value >> is "classically" solved by using a temporary variable and moving of the >> array elements; the latter can be done by using copy(). >> >> 1. https://blog.golang.org/slices-intro >> 2. https://blog.golang.org/slices >> >> -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/e1b21144-07f1-43a5-90b8-038a4b0c5616n%40googlegroups.com.