wasm-bindgen icon indicating copy to clipboard operation
wasm-bindgen copied to clipboard

What's the correct way to iterating a rust exporting struct from a js array?

Open PupilTong opened this issue 2 months ago • 6 comments

https://github.com/PupilTong/wbg_array_element_ownership/blob/main/vitest.test.ts

I have read the issue https://github.com/wasm-bindgen/wasm-bindgen/issues/2231

However the MyStruct::try_from_js_value is not work

I'm not sure what's the correct way to iterate a Array without importing a javascript helper function.

PupilTong avatar Nov 03 '25 06:11 PupilTong

the pub fn get_struct_value_sum(arr: Vec<MyStruct>) causes the ownership move from JS to rust.

However the Vec<&T> and JsValue downcasting are not supported yet.

looks like I have to map the array in JS manually?

PupilTong avatar Nov 03 '25 07:11 PupilTong

Do not run a second round, as ownership has been transferred. Here are some details: https://github.com/wasm-bindgen/wasm-bindgen/issues/4289#issuecomment-3476572211

test('array_ownership', () => {
  const struct1 = create_my_struct(10);
  const struct2 = create_my_struct(20);
  const struct3 = create_my_struct(30);
  const arr = [struct1, struct2, struct3];
  const sum1 = get_struct_value_sum(arr);
  expect(sum1).toBe(60);
  // const sum2 = get_struct_value_sum(arr);
  // expect(sum2).toBe(60);
});

test('array_ownership_downcast', () => {
  const struct1 = create_my_struct(10);
  const struct2 = create_my_struct(20);
  const struct3 = create_my_struct(30);
  const arr = [struct1, struct2, struct3];
  const sum1 = get_value_sum_with_downcast(arr);
  expect(sum1).toBe(60);
  // const sum2 = get_value_sum_with_downcast(arr);
  // expect(sum2).toBe(60);
});

Spxg avatar Nov 03 '25 07:11 Spxg

@Spxg Thanks for your answer.

It dose make sense as the signature of the fn is Vec<T>.

But what we actually need is the foo(t:Vec<&T>).

Leaking the ownership concept to the JavaScript world is a bit weird, especially there is no way to do t.clone() in the JavaScript world.

PupilTong avatar Nov 03 '25 07:11 PupilTong

However the Vec<&T> and JsValue downcasting are not supported yet.

It might be possible to support this case by implementing the corresponding ABI support for exported structs.

guybedford avatar Nov 03 '25 17:11 guybedford

Sorry, correction - it wouldn't apply to exported arguments due to the ownership model.

The fix might actually be to define this as an imported struct, so that it can be treated as a JS struct with arbitrary GC references, even though the struct is an internally defined one.

guybedford avatar Nov 03 '25 17:11 guybedford

update: wasm-bindgen-derive works for me

PupilTong avatar Nov 04 '25 11:11 PupilTong