原文
Hit Run on any sample — it executes right in your browser, no install. Gossamer's VM is compiled to WebAssembly.
fn double(x: i64) -> i64 { x * 2 }
fn add(a: i64, b: i64) -> i64 { a + b }
fn clamp(lo: i64, hi: i64, x: i64) -> i64 {
if x < lo { lo } else if x > hi { hi } else { x }
}
fn main() {
let n = 3 |> double |> add(10) |> clamp(0, 100)
println!("answer: {}", n)
}
// A request router - the heart of a web service, runnable right here.
fn route(method: &String, path: &String) -> String {
if method == &"GET" && path == &"/" { "200 Gossamer" }
else if method == &"GET" && path == &"/health" { "200 ok" }
else if method == &"POST" && path == &"/users" { "201 created" }
else { "404 not found" }
}
let requests = [("GET", "/"), ("GET", "/health"), ("POST", "/users"), ("GET", "/x")]
for (m, p) in requests {
println!("{} {} -> {}", m, p, route(&m, &p))
}
fn fib(n: i64) -> i64 {
if n < 2 { n } else { fib(n - 1) + fib(n - 2) }
}
fn main() {
// spawn runs fib on a goroutine; join collects its result.
let h = spawn(|| fib(30))
match h.join() {
Ok(v) => println!("fib(30) on a goroutine = {}", v),
Err(e) => eprintln!("worker failed: {}", e),
}
}
use std::strings
enum Shape {
Circle(f64),
Rect { w: f64, h: f64 },
Triangle(f64, f64),
}
fn area(s: &Shape) -> f64 {
match s {
Shape::Circle(r) => 3.14159 * r * r,
Shape::Rect { w, h } => w * h,
Shape::Triangle(b, h) => 0.5 * b * h,
}
}
// Top-level statements - no fn main() needed
let shapes = [Shape::Circle(3.0), Shape::Rect { w: 4.0, h: 5.0 }, Shape::Triangle(6.0, 2.0)]
for s in shapes {
println!("area = {:.2}", area(&s))
}