Make Rust tree type polymorphic
This commit is contained in:
parent
58005ee261
commit
71e4ffaede
25
rust/lib.rs
25
rust/lib.rs
@ -1,6 +1,9 @@
|
|||||||
#![allow(dead_code)]
|
#![allow(dead_code)]
|
||||||
|
|
||||||
use std::ffi::{CStr, c_char};
|
use std::{
|
||||||
|
ffi::{CStr, c_char},
|
||||||
|
ops::Add,
|
||||||
|
};
|
||||||
|
|
||||||
fn say_hello(name: &str) {
|
fn say_hello(name: &str) {
|
||||||
println!("Hello from Rust, {name}!");
|
println!("Hello from Rust, {name}!");
|
||||||
@ -42,12 +45,20 @@ extern "C" fn add(a: i64, b: i64) -> i64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[repr(C)]
|
#[repr(C)]
|
||||||
enum BTree {
|
enum BTree<A> {
|
||||||
Leaf { value: i64 },
|
Leaf {
|
||||||
Fork { left: Box<BTree>, right: Box<BTree> },
|
value: A,
|
||||||
|
},
|
||||||
|
Fork {
|
||||||
|
left: Box<BTree<A>>,
|
||||||
|
right: Box<BTree<A>>,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
impl BTree {
|
impl<A> BTree<A>
|
||||||
fn sum(&self) -> i64 {
|
where
|
||||||
|
A: Add<Output = A> + Copy,
|
||||||
|
{
|
||||||
|
fn sum(&self) -> A {
|
||||||
match self {
|
match self {
|
||||||
BTree::Leaf { value } => *value,
|
BTree::Leaf { value } => *value,
|
||||||
BTree::Fork { left, right } => left.sum() + right.sum(),
|
BTree::Fork { left, right } => left.sum() + right.sum(),
|
||||||
@ -68,5 +79,5 @@ enum BTreeC {
|
|||||||
|
|
||||||
#[unsafe(no_mangle)]
|
#[unsafe(no_mangle)]
|
||||||
extern "C" fn sum_tree(t: BTreeC) -> i64 {
|
extern "C" fn sum_tree(t: BTreeC) -> i64 {
|
||||||
(unsafe { std::mem::transmute::<_, &BTree>(&t) }).sum()
|
(unsafe { std::mem::transmute::<_, &BTree<i64>>(&t) }).sum()
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user