Thanks for the replies.

I had been trying to translate the trick from C into Go where you can find 
how many structures are in an initialized array of structures
by dividing the size of the array by the size of one structure. As I've 
learned, not only isn't this possible, because you can't get
the size of one structure, but also because it isn't necessary. Instead, 
using a slice of structures rather than an array, I can just do 
"len(structslice)".
That gives me what I need.

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 
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.

Cordially,
Jon Forrest

On Sunday, October 24, 2021 at 11:29:58 AM UTC-7 filipdimi...@gmail.com 
wrote:

> len() works on indexed types - arrays, slices, maps, strings. It also 
> works on buffered channels but we can consider that a sequence. I don't 
> consider a struct a sequence. It's non-obvious what the behaviour would be. 
> Both of these sound reasonable: len() should be the memory size of the 
> struct like sizeof in C/C++ *or* it should be the sum of the lengths of its 
> (sequence) members.
>
> The first case is way too low-level for Go, because it belongs to an 
> unsafe operation so that's an easy no, ... and it already exists as 
> unsafe.Sizeof().
>
> The second case (len being the sum of its members' lengths) would require 
> recursive calls, and almost surely infinite cycles as we eventually get to 
> pointers. 
>
> On Sunday, October 24, 2021 at 8:11:37 PM UTC+2 jlfo...@berkeley.edu 
> wrote:
>
>> I noticed that the len() function doesn't take a struct as an argument 
>> (see below).
>> This is a big surprise. Can someone shed some light on why this 
>> restriction exists?
>>
>> Cordially,
>> Jon Forrest
>>
>> ----------
>> package main
>>
>> import "fmt"
>>
>> var s struct {
>>         i1      int
>>         i2      int
>> }
>>
>> func main() {
>>        fmt.Printf("len(s) = %d\n", len(s)) // -- invalid argument s (type 
>> struct { i1 int; i2 int }) for len
>> }
>>
>

-- 
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/7df80e52-aa43-44f3-a730-e91beb25264dn%40googlegroups.com.

Reply via email to