In golang spec, if it cast the variable, pointer that cast returns is changed?

86 views
Skip to first unread message

Tomoya Kuwayama

unread,
Oct 10, 2023, 8:04:03 AM10/10/23
to golang-nuts
Hello!

In golang spec, if it cast the variable, pointer that cast returns is changed?
Consider the following code. Do the pointers `before` and `after` hold different values?

```go
package main

import "fmt"

type DefinedInt int

func main() {
var before int
before = 1

after := DefinedInt(before)

fmt.Printf("before: %p\n", &before)
fmt.Printf("after : %p\n", &after)
}
```

Michel Levieux

unread,
Oct 10, 2023, 8:34:32 AM10/10/23
to Tomoya Kuwayama, golang-nuts
Hi,

Note that this has nothing to do with casting. `after` and `before` are not pointers, they're plain old `int` variables (or `DefinedInt` in your example but that does not change anything). When you do `after := whatever`, you're declaring (and assigning) a new variable `after` to hold the same value as `before`, which does not mean in any way that `after` and ` before` will have the same memory address. Look at the following code: https://go.dev/play/p/yacBcIWpiar

If you want variables pointing to the same memory address, you have to use pointers explicitly, as in: https://go.dev/play/p/hcse5k-vD4E

Hope that helps!

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/8677311d-a056-41f6-a81c-ad1286c71d8an%40googlegroups.com.

Soigner, c’est bien plus qu’un métier.
The information transmitted, including attachments, is intended only for the person(s) or entity to which it is addressed and may contain confidential and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and destroy any copies of this information.
Reply all
Reply to author
Forward
0 new messages