File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -41,9 +41,13 @@ fn (mut g Gen) struct_init(node ast.StructInit) {
4141 mut sym := g.table.final_sym (unwrapped_typ)
4242 if sym.kind == .sum_type {
4343 if node.typ.has_flag (.generic) && unwrapped_typ.is_ptr () {
44- g.write ('&(' )
45- g.write (g.type_default_sumtype (unwrapped_typ.set_nr_muls (0 ), sym))
46- g.write (')' )
44+ // handle promotions to a sumtype for generic functions like this one: `fn (d Struct) a[T]() T { return d }`
45+ // the value should be on the heap, since it is not known where it will be used:
46+ sumtype_type := unwrapped_typ.set_nr_muls (0 )
47+ sumtype_name := g.styp (sumtype_type)
48+ g.write ('HEAP(${sumtype_name }, (' )
49+ g.write (g.type_default_sumtype (sumtype_type, sym))
50+ g.write ('))' )
4751 } else {
4852 g.write (g.type_default_sumtype (unwrapped_typ, sym))
4953 }
Original file line number Diff line number Diff line change 1+ struct Struct {}
2+
3+ type SumType = Struct | int
4+
5+ fn (d Struct) a [T]() T {
6+ return T{}
7+ }
8+
9+ fn test_main () {
10+ s := Struct{}
11+ x := s.a[& SumType]()
12+ assert x is Struct
13+ println ('first assert passed' )
14+ println (x)
15+ assert x is Struct
16+ println ('second assert passed' )
17+ }
You can’t perform that action at this time.
0 commit comments