Skip to content

cmd/go2go: generic struct embedding doesn't seem to work as expected #39678

@beoran

Description

@beoran

I was playing arund in the go2go playground to see if I could generically add methods to a type,
using struct embedding, but it didn't work as I expected it would.
See the following example, it does not compile with an error: "./prog.go2:9: undefined: T",
but I think it should work correctly. I also can't use the BaseData type as I expected I could.
Is this by design or is there another way to do what I want to do?

package main

import (
	"fmt"
)

// Trying to generically add methods to a data type.
type Base(type T) struct {
	T
}

// The method generically implemented
func (b Base(T)) Foo() {
	fmt.Printf("Foo: %v\n", b.T)
}

type Data struct {
	Count int
}

type BaseData Base(Data)

func main() {
	// p := BaseData{} : doesn't work
	p := Base(Data){}
	p.Count = 7
	p.Foo()
}

https://go2goplay.golang.org/p/PpLEuAoRWIm

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.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions