6

if I annotated the fmt.Printf code, the output will be false. but if uncomment the two lines code , it will be true.

why? may the fmt.Printf worked?

this is the code:

package main

import "fmt"

func main() {
    type s struct{}
    s1 := new(s)
    s2 := new(s)
    // fmt.Printf("%p\n", s1)
    // fmt.Printf("%p\n", s2)
    fmt.Println(s1 == s2)
}

i know all the struct{} instance has the same addr, so it should be true always.

shaominyao
  • 75
  • 1
  • 5
    *"so it should be true always."* -- No, not always. The last sentence all the way at the bottom of the [spec](https://go.dev/ref/spec#Size_and_alignment_guarantees) reads: *"Two distinct zero-size variables __may__ have the same address in memory."* MAY is not MUST. – mkopriva Jul 04 '23 at 03:18
  • Maybe right u said. But this scenario can be reproduced stably。 like u said, it should be accidental。 – shaominyao Jul 04 '23 at 03:23
  • 1
    See related answers: https://stackoverflow.com/questions/52421103/why-struct-arrays-comparing-has-different-result/52421277#52421277 and https://stackoverflow.com/questions/48052722/addresses-of-slices-of-empty-structs/48053270#48053270 – mkopriva Jul 04 '23 at 03:34
  • The reason why the output is false is because the compiler is not able to determine the address of the struct{} instance at compile time. This is because the struct{} type does not have any fields, and therefore its size is zero. The compiler cannot allocate memory for a zero-sized type, so it has to use a different representation for struct{} instances. – Vishwa Ratna Jul 04 '23 at 04:37
  • The reason why the output is true when you uncomment the fmt.Printf lines is because the fmt.Printf function prints the address of the struct{} instance at runtime. This address is the same for all struct{} instances, so the compiler is able to compare them for equality. – Vishwa Ratna Jul 04 '23 at 04:37
  • 2
    The fact that something *may* be true does not mean that it *must* be true, or that there should be any randomness to whether it's true. The implementation can pick whatever is convenient. – user2357112 Jul 04 '23 at 04:38
  • 3
    If 2 things _may or may not_ be equal by the spec, that means you cannot assume anything regarding to that. Period. – icza Jul 04 '23 at 06:19

0 Answers0