Return an object from Rust to javascript

I've started to do a program in Rust and WebAssembly to sort 3 strings and print the output.I use a vector to store these 3 strings together.After i perform sorting i need to return an object to javascript and i need to display as three strings in sorted order in my browser. But when i implement my code i'm not getting output. So, please help me with correct code.

mod utils;

#[macro_use]
extern crate serde_derive;
 use web_sys::console;
use wasm_bindgen::prelude::*;
// use std::io;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;


#[derive(Serialize)]
pub struct Example 
{
    pub v: Vec<String>,
}

    #[wasm_bindgen]
    
    pub fn sortbu(s1: &str,s2: &str,s3: &str)->JsValue
    {
        let mut v: Vec<String>=Vec::new();
        let str1=s1.to_string();
        let str2=s2.to_string();
        let str3=s3.to_string();

        v.push(str1);
        v.push(str2);
        v.push(str3);

        for i in 0..v.len()
        {
            let mut k=3-i-1;
            for j in 0..k
            {
                if v[j]>v[j+1]
                {
                    let mut t=String::new();
                    let t=v[j].clone();
                    v[j]=v[j+1].clone();
                    v[j+1]=t.clone();
                }
            }
        }
       
        let example = Example
        {
           v
        };
        
    JsValue::from_serde(&example).unwrap()
    
}

import * as wasm from "wasm-game-of-life";

const s=document.getElementById("b");

s.addEventListener("click",event=>{
    const a=document.getElementById("a1").value;
    const b=document.getElementById("a2").value;
    const c=document.getElementById("a3").value;
    const ans=wasm.sortbu(a,b,c);
    alert(ans);
    document.getElementById("re").value=ans;
});

Have you verified that the javascript click handler is actually called? And that the browser console doesnt contain any errors?

yes, the javascript click handler is called. And the browser doesn't contains any error.

document.getElementById("re").value=ans;

after this statement, in text box result is like [object object]

This is not a problem with rust, this is a problem of handling returned value in JS.

You are returning the struct. This struct is converted into JS object. When this JS object is used as the DOM element value, it is converted to string, but, as JS doesn't know how to do this, it performs the conversion in the general way, returning this [object Object] you.re seeing.

What you probably want is something like this:

document.getElementById("re").value = ans.v.join(", ")

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