O
O
Oleg2020-06-28 19:56:19
go
Oleg, 2020-06-28 19:56:19

Why are different addresses displayed as a result?

Exaggerated part of my code before this:

link to the sandbox

package main

import "fmt"

type Test struct {
  array []Array
}

type Array struct {
  value float32
}

func (t *Test) Testing() {
  for i, a := range t.array {
    if i == 0 {
      fmt.Printf("%T %v\n", a, &a.value)
      fmt.Printf("%T %v\n", t.array[i], &t.array[i].value)
    }
  }
}

func main() {
  t := Test{}
  t.array = make([]Array, 3)
  t.Testing()
}


Sample result:
main.Array 0xc00010000c
main.Array 0xc000114000

Why does the result show different addresses?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2020-06-28
@zigenzoog

This happens because you store values, not pointers, and, accordingly, here in `a` - a copy of value is created. In order for the addresses to be the same, you need to store pointers, not values, i.e. you have to do it like thisfor i, a := range t.array

type Test struct {
  array []*Array
}

Corrected your code in the sandbox , now the addresses are the same

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question