On Mon, Feb 22, 2021 at 3:04 PM Khosrow Afroozeh <kh.afroo...@gmail.com>
wrote:

> 2. It seems impossible to implement a type-safe Map function. The
> following code:
>
> func (l List[T]) Map(f func[U any](v T) U) List[U] {
>     return nil
> }
>
> will not compile, with the error: function type cannot have type
> parameters
> Judging by the error message this seems to be by design, but it will
> significantly reduce the usability of generics for any transformation
> method. What is the reasoning behind this limitation?
>

You are correct that it reduces expressive power. That has been deemed
acceptable, for now. Some of the reasoning is in the design doc:
https://go.googlesource.com/proposal/+/master/design/go2draft-type-parameters.md#No-parameterized-methods
This is also related to the restriction that generic functions and types
can't be used without instantiation, which is very hard to figure out with
reflection existing, the requirement to not generate code at runtime and
the strong preference not to force certain implementation options
(specifically boxing).

If you could add type-parameters to methods, you could effectively achieve
the same result though, by doing (making up syntax for generic methods)

type F struct {}

func (F) DoSomething[T any](v T) {
}

func main() {
    var f F
}

`f` now is effectively an uninstantiated generic function - you just have
to write the call as `f.DoSomething(v)`, not `f(v)`.
The corollary is, that all the semantic and implementation difficulties
arising from uninstantiated generic functions and types *also* arise from
allowing additional type-parameters on methods.

No one argues it wouldn't be useful. But it's hard to do.


>
> Thanks,
>
> --
> 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/2aa1c2cb-e7bc-438e-81a9-e4a2904af21cn%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/2aa1c2cb-e7bc-438e-81a9-e4a2904af21cn%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
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/CAEkBMfF9_uqwymPZtg6V%2B4%3DW-satN7wM6%3DN_rhxR%3D%3Dg25Ew_Bg%40mail.gmail.com.

Reply via email to