On Sun, Oct 24, 2021 at 4:45 PM
jlfo...@berkeley.edu
<
jlfo...@berkeley.edu> wrote:
>
> But, I still have some questions about the responses. First, I think the expected value of len(struct) should be its size, in bytes,
> like with a string. Are there any examples of problems this would cause?
I believe that that would be surprising. For example,
unsafe.Sizeof("") == 16 (on a 64-bit platform) but len("") == 0. len
always returns the number of elements contained in some aggregate
type, not the size of a value of that type. So if we supported len on
a struct type, I think the most natural value to return would be the
number of fields, not the total size of the struct. But of course
that isn't very useful in practice, so we simply don't support len on
a struct type.
> I don't understand why this has to be
> unsafe. (It could even be done at compile time). I also don't understand the comment about recursive calls. Since it's possible
> to assign one structure to another I would think that the structure length is known. Since I'm new to Go I'm probably
> not aware of the finer points that would make this not so.
The size of a struct type is indeed known at compile time, and
unsafe.Sizeof applied to a struct type returns a constant that is the
size of the struct. You're right in that this does not really have to
be in unsafe (and you can get the same value using the reflect package
without using unsafe, although the result will be not technically be a
constant--it will always be the same value, but you can't use it to
set the size of an array). unsafe.Sizeof is in unsafe mainly for
historical reasons and because there wasn't anywhere else natural to
put it.
Ian