From 2d655fb15a50036547a6bf8f77608aab9fb31368 Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Sat, 16 Jul 2022 15:51:25 -0700 Subject: [PATCH] unsafe: document when Sizeof/Offsetof/Alignof are not constant They are not constant if their arguments have types that are variable size. Fixes #53921 Change-Id: I2d46754c27f55a281331c099a11ea3cd85ec4e89 Reviewed-on: https://go-review.googlesource.com/c/go/+/417917 Auto-Submit: Ian Lance Taylor Run-TryBot: Ian Lance Taylor Run-TryBot: Ian Lance Taylor Reviewed-by: Dmitri Shuralyov Reviewed-by: Rob Pike TryBot-Result: Gopher Robot Reviewed-by: Ian Lance Taylor --- src/unsafe/unsafe.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/unsafe/unsafe.go b/src/unsafe/unsafe.go index da15902b29..5051b3ee9f 100644 --- a/src/unsafe/unsafe.go +++ b/src/unsafe/unsafe.go @@ -189,13 +189,18 @@ type Pointer *ArbitraryType // For instance, if x is a slice, Sizeof returns the size of the slice // descriptor, not the size of the memory referenced by the slice. // For a struct, the size includes any padding introduced by field alignment. -// The return value of Sizeof is a Go constant. +// The return value of Sizeof is a Go constant if the type of the argument x +// does not have variable size. +// (A type has variable size if it is a type parameter or if it is an array +// or struct type with elements of variable size). func Sizeof(x ArbitraryType) uintptr // Offsetof returns the offset within the struct of the field represented by x, // which must be of the form structValue.field. In other words, it returns the // number of bytes between the start of the struct and the start of the field. -// The return value of Offsetof is a Go constant. +// The return value of Offsetof is a Go constant if the type of the argument x +// does not have variable size. +// (See the description of [Sizeof] for a definition of variable sized types.) func Offsetof(x ArbitraryType) uintptr // Alignof takes an expression x of any type and returns the required alignment @@ -206,7 +211,9 @@ func Offsetof(x ArbitraryType) uintptr // within that struct, then Alignof(s.f) will return the required alignment // of a field of that type within a struct. This case is the same as the // value returned by reflect.TypeOf(s.f).FieldAlign(). -// The return value of Alignof is a Go constant. +// The return value of Alignof is a Go constant if the type of the argument +// does not have variable size. +// (See the description of [Sizeof] for a definition of variable sized types.) func Alignof(x ArbitraryType) uintptr // The function Add adds len to ptr and returns the updated pointer -- 2.48.1