Skip to content

Commit cc4773e

Browse files
committed
Support new() built-in for type params.
For the most part it already worked through the $newDataPointer(), I only had to update it to handle pointers to array, which are a wrapped type.
1 parent bfa92fe commit cc4773e

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

compiler/prelude/types.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -855,7 +855,7 @@ var $ptrType = elem => {
855855
};
856856

857857
var $newDataPointer = (data, constructor) => {
858-
if (constructor.elem.kind === $kindStruct) {
858+
if (constructor.elem.kind === $kindStruct || constructor.elem.kind === $kindArray) {
859859
return data;
860860
}
861861
return new constructor(() => { return data; }, v => { data = v; });

tests/typeparams/builtins_test.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package typeparams_test
22

33
import (
44
"fmt"
5+
"reflect"
56
"testing"
67
)
78

@@ -163,3 +164,37 @@ func TestCap(t *testing.T) {
163164
})
164165
}
165166
}
167+
168+
func _new[T any]() *T {
169+
return new(T)
170+
}
171+
172+
func TestNew(t *testing.T) {
173+
type S struct{ i int }
174+
175+
tests := []struct {
176+
desc string
177+
got any
178+
want any
179+
}{{
180+
desc: "struct S",
181+
got: *_new[S](),
182+
want: S{},
183+
}, {
184+
desc: "[3]int",
185+
got: *_new[[3]int](),
186+
want: [3]int{},
187+
}, {
188+
desc: "int",
189+
got: *_new[int](),
190+
want: int(0),
191+
}}
192+
193+
for _, test := range tests {
194+
t.Run(test.desc, func(t *testing.T) {
195+
if !reflect.DeepEqual(test.got, test.want) {
196+
t.Errorf("Got: new(%T) = %#v. Want: %#v.", test.want, test.got, test.want)
197+
}
198+
})
199+
}
200+
}

0 commit comments

Comments
 (0)