Beginner's question on why two slices don't share the underlying storage

168 views
Skip to first unread message

____

unread,
Jul 31, 2020, 11:47:50 AM7/31/20
to golang-nuts
Hi all,

I would appreciate it if someone could help me understand what exactly I'm doing in the code below. My experience with Go spans a few weekends in total so please bear with the naiveté of my question.

When I do this


the factory and the gadget share the same specs. When I do this 


they don't. 

Question: What is the proper way to reason about this code?

I'm mostly looking for an efficient mental model that makes an expert go "of course...", because I've been trying to track references and pointers in my head with no success.

On a different note---my apologies if I sound cheesy---thank you for making and generously sharing Go. I think you can tell a good piece of engineering when it puts a smile on your face.

Thanks in advance.

Ian Lance Taylor

unread,
Jul 31, 2020, 12:09:21 PM7/31/20
to ____, golang-nuts
On Fri, Jul 31, 2020 at 8:47 AM ____ <karath...@gmail.com> wrote:
>
> I would appreciate it if someone could help me understand what exactly I'm doing in the code below. My experience with Go spans a few weekends in total so please bear with the naiveté of my question.
>
> When I do this
>
> https://play.golang.org/p/rQvmZEqq8tp
>
> the factory and the gadget share the same specs. When I do this
>
> https://play.golang.org/p/-Gi5N-kpKFq
>
> they don't.
>
> Question: What is the proper way to reason about this code?
>
> I'm mostly looking for an efficient mental model that makes an expert go "of course...", because I've been trying to track references and pointers in my head with no success.

A slice is a struct that contains a pointer to an underlying array.
When you change a slice, you change the pointer. When you change an
element of a slice, you change an element of the underlying array.

It may help to read https://blog.golang.org/slices-intro.

Ian

Isaiah

unread,
Aug 1, 2020, 2:16:25 AM8/1/20
to golang-nuts
Thank you very much. All clear now.
Reply all
Reply to author
Forward
0 new messages