After reading a bit I came to the conclusion:
- Aligned should include the structs.HostLayout field. And T of course
too.
- Aligned must be allocated on heap, since the stack might be moved.
- And as said, T must not contain any heap pointers.
Then this *should* be ok with the current version of Go.
Timur Celik schrieb am Dienstag, 10. Juni 2025 um 17:03:31 UTC+2:
> Consider the following generic type, which ensures to be large enough by
> allocating enough padding A and the to-be-aligned type T:
>
> type Alignment interface {
> Align16 | Align64
> }
> type Align16 = [16]byte
> type Align64 = [64]byte
>
> type Aligned[T any, A Alignment] struct {
> pad A
> val T
> }
>
> func (p *Aligned[T, A]) Value() *T {
> size := unsafe.Sizeof(*new(A))
> align := size - uintptr(unsafe.Pointer(&p.pad[0]))&(size-1)
> return (*T)(unsafe.Pointer(&p.pad[align]))
> }
>
> Under the assumption that T has no heap pointers, is this safe? Or asked
> in another way, under which circumstances would this break?
>
--
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 [email protected].
To view this discussion visit
https://groups.google.com/d/msgid/golang-nuts/c6a7f5a5-a6f9-4989-a07d-76cb392b1777n%40googlegroups.com.