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/2bf465ca-68ba-4f20-820b-f93c485bda93n%40googlegroups.com.

Reply via email to