Thank you! I've now switched to using any as you suggested & also use
strings.Builder.
On Wednesday, November 9, 2022 at 4:33:48 PM UTC dun...@harris3.org wrote:
> > Interestingly, I couldn't put the asStr() code in the String() function
> since doing so produced this error:
> >
> > invalid
> Interestingly, I couldn't put the asStr() code in the String() function
since doing so produced this error:
>
> invalid operation: cannot use type assertion on type parameter value
element (variable of type T constrained by comparable)
You need to convert to "any":
Thanks for your help and very interesting ideas. In the end I used this:
type Set[T comparable] map[T]struct{}
func New[T comparable](elements ...T) Set[T] {
set := make(Set[T], len(elements))
for _, element := range elements {
set[element] = struct{}{}
}
return set
}
If you're sure that T is an int or a string, then why not constrain it as
such? https://go.dev/play/p/1kT6EacMHco
You could go further and constrain it to allow any type with ordering
defined: https://go.dev/play/p/il5koj1RPkh
If you want to allow any kind of comparable key in your set, one
On Tue, Nov 8, 2022 at 10:56 AM 'Mark' via golang-nuts
wrote:
> // Want to sort by T < T //
> elements := make([]string, 0, len(me))
> for element := range me {
> elements = append(elements, fmt.Sprintf("%#v", element))
> }
> sort.Strings(elements)
I see that your example works, but I can't see how to adapt it to my use
case.
type Set[T comparable] map[T]struct{}
func New[T comparable](elements ...T) Set[T] {
set := make(Set[T], len(elements))
for _, element := range elements {
set[element] = struct{}{}
}
return
On Tue, Nov 8, 2022 at 9:53 AM 'Mark' via golang-nuts
wrote:
> Given a function:
>
> func F[T comparable](a T) {
> }
>
> is it possible to check T's type inside F?
>
> My use case is that I have a function with signature G[T comparable](x []T)
> and inside G I want to sort the elements in slice
Given a function:
func F[T comparable](a T) {
}
is it possible to check T's type inside F?
My use case is that I have a function with signature G[T comparable](x []T)
and inside G I want to sort the elements in slice x where T could be int or
string.
This arises in a tiny generic set module