On Monday, November 4, 2024 at 1:47:30 PM UTC+8 Ian Lance Taylor wrote:

On Sun, Nov 3, 2024 at 12:41 AM hey...@gmail.com <hey...@gmail.com> wrote: 
> 
> Not sure generic type alias is the solution, but what I'm trying to do is 
I have a type like this 
> 
> type Map[K comparable, V any] struct { m map[K]V } 
> 
> and I want it to implement json.Unmarshaller to decode json objects, when 
K's underlying type is string: 
> 
> type omap[K ~string, V any] = Map[K, V] 
> func (m *omap[K, V]) UnmarshalJSON(data []byte) error { 
> k := "a" 
> v :=1 
> m[K(k)] = v 
> } 
> 
> Go 1.23 with the aliastypeparams flag enabled, currently complains 
"cannot convert k (variable of type string) to type K". 
> 
> I wonder if using alias this way is wrong and if there exists another 
solution? 

A type alias is just an alias. When you declare a method on the alias 
map, you are declaring a method on the type Map. That means that the 
~string in the omap definition is ignored for the method definition; 
all that matters is the comparable constraint in the Map definition. 
You can't in general convert a string to a comparable type. 

Ian 


There is a little weirdness here. Maybe delcaring method on geneirc aliases 
should be forbidden.

-- 
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 visit 
https://groups.google.com/d/msgid/golang-nuts/b8a3f3c7-feb2-4367-9390-b8258f5809a4n%40googlegroups.com.

Reply via email to