Skip to content

Make NewStringList to accept parametrized slice #1293

@gudvinr

Description

@gudvinr

To be able to use list of types whose base type is string you will need to resort to NewDynamicList:

type NotString string
...
types.NewDynamicList(adapter, []NotString{"cake", "croissant"})
...

NewDynamicList uses reflection which can be avoided for such cases.

Another option is to convert []NotString to []string and use NewStringList which will force you to allocate same slice twice.


However, quite simple modification like this one makes it possible to use these slices as is:

func NewStringList[T ~string](adapter Adapter, elems []T) traits.Lister {
...
get: func(i int) any { return string(elems[i]) },
...
}
...
types.NewStringList(adapter, []NotString{"cake", "croissant"})

In addition to that, something like this can make life easier for types whose natural representation is string but internal representation is not. Some examples of which are x509.OID and its brother asn1.ObjectIdentifier. Both and many others implement fmt.Stringer.

This can be resolved with this:

func NewStringerList[T fmt.Stringer](adapter Adapter, elems []T) traits.Lister {
...
get: func(i int) any { return elems[i].String() }
...
}

Currently, for this case you can't even use NewDynamicList because these types don't represent any "native" type. So you either make another type for therm (and re-allocate slice before passing) or work-around using NewProtoList and wrapper that implements protoreflect.List.

Or, instead of using baseList one could also make traits.Lister implementation but that creates enormous boilerplate.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions