On Tue, Jan 24, 2023 at 12:01 PM nc <nchell...@gmail.com> wrote:
>
> I have some sample code here: https://play.golang.com/p/H4kOGxamk0_D
>
> I have used a pattern in the above playground snippet (twice: once in 
> uniqueValues() and once in keys()) that declares and initializes a slice 
> like: s := make([]T, 0, knownLength) . Then it ranges over something 
> containing knownLength elements and assigns them to s using append. The thing 
> I like about this pattern is that I don't need an index variable in my range 
> loop and I can just get away with using append(). I am trying to avoid the 
> need to extend the array underlying s when calling append and more generally 
> to do this initialization efficiently and with a minimum of code. This is 
> also my first bit of code using generics.

This technique, of make([]type, 0, len) followed by an append loop, is
a common one.  Personally I always use that technique if the loop
statement is at all complicated, such as if it has any sort of if
statement.  For very simple loops like the ones in your example I
might just use make([]type, len) and then assign, but using append is
also good.  In my opinion.


> I'm also wondering a couple of other questions that are less important to me 
> right now but that I would still very much appreciate having answered:
>
> 1. Is my use of generics reasonable here?

Seems fine to me.  Minor syntax point: you don't have to write "T
comparable, U comparable", you can write "T, U comparable".

Ian

-- 
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/CAOyqgcXJsmFP6Pv3uHiW-EY2BRjvty%3D5fNTFibOaLgvbz2CKbQ%40mail.gmail.com.

Reply via email to