Skip to content

Commit 0769076

Browse files
committed
Implement type param to map conversion.
1 parent 772d85d commit 0769076

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

compiler/prelude/types.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,8 @@ var $newType = (size, kind, string, named, pkg, exported, constructor) => {
472472
typ.convertFrom = (src) => $convertToStruct(src, typ);
473473
break;
474474
case $kindMap:
475+
typ.convertFrom = (src) => $convertToMap(src, typ);
476+
break;
475477
case $kindChan:
476478
case $kindFunc:
477479
break;
@@ -1190,4 +1192,14 @@ const $convertToArray = (src, dstType) => {
11901192
// Since arrays are passed by value, the conversion result must be a copy
11911193
// of the original value, even if it is the same type.
11921194
return $clone(src.$val, dstType);
1195+
};
1196+
1197+
/**
1198+
* Convert to map types.
1199+
*
1200+
* dstType.kind must be $kindMap. Src must be a wrapped map value. Returned
1201+
* value will always be a bare JavaScript object representing the map.
1202+
*/
1203+
const $convertToMap = (src, dstType) => {
1204+
return src.$val;
11931205
};

tests/typeparams/conversion_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ type ( // Named types for use in conversion test cases.
5656
sl []byte
5757
arr [3]byte
5858
arrPtr *[3]byte
59+
m map[string]string
5960
)
6061

6162
type numeric interface {
@@ -257,6 +258,15 @@ func (tc arrayConversion[srcType, dstType]) Run(t *testing.T) {
257258
checkConversion(t, tc.src, dstType(tc.src), tc.want)
258259
}
259260

261+
type mapConversion[srcType ~map[string]string, dstType ~map[string]string] struct {
262+
src srcType
263+
want dstType
264+
}
265+
266+
func (tc mapConversion[srcType, dstType]) Run(t *testing.T) {
267+
checkConversion(t, tc.src, dstType(tc.src), tc.want)
268+
}
269+
260270
func TestConversion(t *testing.T) {
261271
strVar := "abc"
262272
stVar := st{s: "abc", i: 42}
@@ -359,6 +369,9 @@ func TestConversion(t *testing.T) {
359369
}]{src: st{i: 42, s: "abc"}, want: st2{s: "abc", i: 42}},
360370
// $convertToArray
361371
arrayConversion[[3]byte, arr]{src: [3]byte{1, 2, 3}, want: arr{1, 2, 3}},
372+
// $convertToMap
373+
mapConversion[map[string]string, m]{src: map[string]string{"abc": "def"}, want: m{"abc": "def"}},
374+
mapConversion[map[string]string, m]{src: nil, want: nil},
362375
}
363376

364377
for _, test := range tests {

0 commit comments

Comments
 (0)