Skip to content

cmd/compile: pointer method example fails type interference when defined as a struct's method #63708

@mitar

Description

@mitar

I am looking at the pointer method example from generics doc. There it states:

This approach works as expected, but it is awkward to have to repeat Settable in the type arguments. Fortunately, constraint type inference makes it less awkward.

But if I convert that example into methods on a struct, the type interference does not make it less awkward. Demo

package main

import "strconv"

type Settable int

func (p *Settable) Set(s string) {
	i, _ := strconv.Atoi(s)
	*p = Settable(i)
}

type Setter[B any] interface {
	Set(string)
	*B // non-interface type constraint element
}

type F[T any, PT Setter[T]] struct{}

func (_ F[T, PT]) FromStrings(s []string) []T {
	result := make([]T, len(s))
	for i, v := range s {
		p := PT(&result[i])
		p.Set(v)
	}
	return result
}

func main() {
	_ = F[Settable, *Settable]{}.FromStrings([]string{"1", "2"})
	_ = F[Settable]{}.FromStrings([]string{"1", "2"})
}

The last line fails compiling. Are there plans to improve this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.compiler/runtimeIssues related to the Go compiler and/or runtime.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions