Explain code array and slice in go

Use this category to discuss the doubts and questions related to the topic Golang on KodeKloud
a := make([]int, 2, 2)

	a[1] = 1

	b := a[:1]

	fmt.Println(a, b)           // a = [0 1] b = [0]
	fmt.Println(cap(a), cap(b)) // cap(a) = 2 , cap(b) = 2

	b = append(b, 42)
	fmt.Println(a, b)           // a = [0,42], b = [0,42]
	fmt.Println(cap(a), cap(b)) // cap(a) = 2 , cap(b) = 2

	b = append(b, 42)
	fmt.Println(a, b)           // a =[0,42] , b = [0,42,42]
	fmt.Println(cap(a), cap(b)) // cap(a) = 2, cap(b) = 4

My question is : when b created from a , b has reference of a and append 42 to b results in [0,42]
and same for a [0 42] but in next line when b appended to again 42 result is [0 42 42] isn’t the results for a should be [0 42 42 ] ??

as per my understanding , when slice created from array has references but not sure do slice from slice having same rule ?

To understand better, change the code like this

	a := make([]int, 2, 2)

	a[1] = 1

	b := a[:1]
	fmt.Printf("a=%p, b=%p\n", a, b)

	fmt.Println(a, b)           // a = [0 1] b = [0]
	fmt.Println(cap(a), cap(b)) // cap(a) = 2 , cap(b) = 2

	b = append(b, 42)
	fmt.Printf("a=%p, b=%p\n", a, b)
	fmt.Println(a, b)           // a = [0,42], b = [0,42]
	fmt.Println(cap(a), cap(b)) // cap(a) = 2 , cap(b) = 2

	b = append(b, 42)
	fmt.Printf("a=%p, b=%p\n", a, b)
	fmt.Println(a, b)           // a =[0,42] , b = [0,42,42]
	fmt.Println(cap(a), cap(b)) // cap(a) = 2, cap(b) = 4

Here I am printing the memory address of the a and b variables after each assignment to b
You will see that the address of b changes after the second append(). This is because it needed to increase capacity, so was reallocated, copied, then the second 42 was appended to the new copy.