1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-26 17:19:06 -05:00
denoland-deno/core/examples/hello_world.rs

55 lines
1.3 KiB
Rust
Raw Normal View History

2021-01-10 21:59:07 -05:00
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
2020-09-23 10:56:36 -04:00
//! This example shows you how to define ops in Rust and then call them from
//! JavaScript.
use deno_core::op_sync;
2020-09-23 10:56:36 -04:00
use deno_core::JsRuntime;
fn main() {
// Initialize a runtime instance
let mut runtime = JsRuntime::new(Default::default());
// Register an op for summing a number array.
2020-09-23 10:56:36 -04:00
runtime.register_op(
"op_sum",
// The op-layer automatically deserializes inputs
// and serializes the returned Result & value
op_sync(|_state, nums: Vec<f64>, _: ()| {
// Sum inputs
let sum = nums.iter().fold(0.0, |a, v| a + v);
// return as a Result<f64, AnyError>
Ok(sum)
2020-09-23 10:56:36 -04:00
}),
);
runtime.sync_ops_cache();
2020-09-23 10:56:36 -04:00
// Now we see how to invoke the op we just defined. The runtime automatically
2020-09-23 10:56:36 -04:00
// contains a Deno.core object with several functions for interacting with it.
// You can find its definition in core.js.
runtime
.execute_script(
"<usage>",
r#"
// Print helper function, calling Deno.core.print()
2020-09-23 10:56:36 -04:00
function print(value) {
Deno.core.print(value.toString()+"\n");
2020-09-23 10:56:36 -04:00
}
const arr = [1, 2, 3];
print("The sum of");
print(arr);
print("is");
print(Deno.core.opSync('op_sum', arr));
2020-09-23 10:56:36 -04:00
// And incorrect usage
try {
print(Deno.core.opSync('op_sum', 0));
2020-09-23 10:56:36 -04:00
} catch(e) {
print('Exception:');
print(e);
}
"#,
)
.unwrap();
}