You are probably thinking about code like this:

var f2 = *f1

Which will make a copy, although not because `f1` is dereferenced, but
because `=` was called on a value.

Dereferencing a pointer gives a reference to the same value, taking
address of the same value will produce a pointer to the same value. So
in expression like this:

var f2 = &(*f1)

`&` and `*` cancel each other out and it can be simplified to:

var f2 = f1

Which means "make a copy of pointer". If you take the address of `f1`
and `f2` you'll see that those are indeed different pointers.

If you're thinking about something like `f(*f1)`, then I believe the
function call will make a copy because arguments are passed by values.
`f(f1)` will make a copy too, but a copy of pointer.

Does that make sense?

сб, 25 июл. 2020 г. в 11:09, chri...@surlykke.dk <christ...@surlykke.dk>:
>
> When running this program:
>
> package main
>
> import (
> "fmt"
> )
>
> type Foo struct {
> i int
> }
>
> func main() {
> var f1 = &Foo{i: 0}
> var f2 = &(*f1)
> f2.i = 1
> fmt.Println(f1, f2)
> }
>
> it yields:
>
> &{1} &{1}
>
> (https://play.golang.org/p/qKtURokUCEW)
>
> I (naively) assumed that the expression
>
> &(*f1)
>
> would, first, create a copy of *f1, and then a pointer to that copy, but 
> evidently f2 becomes a pointer to the same struct as f1. Is this something I 
> should have deduced from the language spec?
>
> best regards Christian Surlykke
>
>
> --
> 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/f427ddf6-f4fc-42f4-bee8-d1dab0fef566n%40googlegroups.com.

-- 
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/CAMteYTa2Qx1Dc0x%2B1iaNi98m6jCKuru2qgBFiHF%3Dik6D65SbMA%40mail.gmail.com.

Reply via email to