pgx icon indicating copy to clipboard operation
pgx copied to clipboard

Add `CollectRowsInto` to allow custom slice types

Open ConsoleTVs opened this issue 8 months ago • 3 comments

This PR adds a new method CollectRowsInto to allow overriding the slice type returned by CollectRows. This change is backwards compatible.

type User struct{}
type Users []User

// ...

CollectRows[User] // -> []User (can't override)
CollectRowsInto[Users] // -> Users (implicit)
CollectRowsInto[Users, User] // -> Users (explicit)

ConsoleTVs avatar Apr 20 '25 23:04 ConsoleTVs

Do I understand correctly that this is to save a type cast or is it doing more? Without tests its a bit hard to follow the intent.

jackc avatar Apr 26 '25 14:04 jackc

Oh yes, it's pure type gimmicks, there's no new logic involved.

ConsoleTVs avatar Apr 28 '25 21:04 ConsoleTVs

As far as I can tell you can do the same by assigning the result of CollectRows with = to a variable of your desired type rather than using := to create it. It saves one line of code (or two if err needs to be declared).

I'm somewhat inclined against adding a public function to save a line of code on the basis of avoiding the increase in API surface unless it was going to be very frequently used. And anyone that is doing that type operation frequently can add this helper function to their project.

jackc avatar May 03 '25 19:05 jackc