Generics: How to use Type approximation for generic structs

Was trying to play with generics and tried using type approximation in the following sample code below with compile errors.

My questions are:

  1. How to use type approximation to a generic struct, see EmbedApprox
  2. Hiow to create a struct that contains a type approximation to another struct, see Contain & Contain2
package main

import "fmt"

type Embed[T any] struct {
	AttrEmbed T
}

type EmbedApprox[T any] interface {
	~Embed[T] // A: compile error: invalid use of ~ (underlying type of Embed[T] is struct{AttrEmbed T})
}

type Contain[T EmbedApprox[T]] struct {
	Embed[T]
	AttrContain T
}

type EmbedApprox2[T any] interface {
	~struct{ AttrEmbed T } // compiles ok
}

type Contain2[T EmbedApprox2[T]] struct { // compiles ok
	Embed[T]
	AttrContain T
}

func main() {
	e := Embed[int]{AttrEmbed: 10}

	c := Contain[Embed[int]]{Embed[int]{AttrEmbed: 10}, AttrContain: 10} // compiles errors

	c2 := Contain2[Embed[int]]{Embed[int]{AttrEmbed: 10}, AttrContain: 10} // compiles errors

	fmt.Println(e, c)
}

Compilation errors:

# github.com/globalflea/trygenerics
./main.go:10:2: invalid use of ~ (underlying type of Embed[T] is struct{AttrEmbed T})
./main.go:30:15: cannot implement EmbedApprox[Embed[int]] (empty type set)
./main.go:30:27: cannot use Embed[int]{…} (value of type Embed[int]) as type Embed[Embed[int]] in struct literal
./main.go:30:65: mixture of field:value and value elements in struct literal
./main.go:32:2: c2 declared but not used
./main.go:32:17: Embed[int] does not implement EmbedApprox2[Embed[int]]
./main.go:32:29: cannot use Embed[int]{…} (value of type Embed[int]) as type Embed[Embed[int]] in struct literal
./main.go:32:67: mixture of field:value and value elements in struct literal

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.