On Sat, May 7, 2022 at 12:34 PM 'Axel Wagner' via golang-nuts <golang-nuts@googlegroups.com> wrote:
> I am assuming this is true, but I couldn't find a definitive answer yet (or > rather, the answers seems bad): Does a pointer into any part of a value keep > the entire value alive? So, e.g. is this code safe? > > type A struct { X int; Y int } > func F() *int { > a := A{42, 23} > return &a.X > } > func G() { > p := F() > a := (*A)(unsafe.Pointer(p)) > fmt.Println(a.Y) > } > > The unsafe.Pointer rules state: > >> (1) Conversion of a *T1 to Pointer to *T2. >> Provided that T2 is no larger than T1 and that the two share an equivalent >> memory layout, this conversion allows reinterpreting data of one type as >> data of another type. > > > Which doesn't apply here, as A is larger than int. ^ Breaking the unsafe rules enables the code to behave non predictably. AFAICT, interior pointers do and must keep the entire allocation block alive, but a sufficiently smart compiler is IMO free to ignore setting of the 23 value - or allocating the actual storage for .Y in F(), because no one can observe it - unless breaking the unsafe rules. -- 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/CAA40n-UTb8YqLVzpg4YkJs0HRrcdoU_nMKegKeux9%3DHBk15hUg%40mail.gmail.com.