Skip to content

Commit

Permalink
Adding variadic fns
Browse files Browse the repository at this point in the history
  • Loading branch information
simsekgokhan committed Feb 8, 2024
1 parent 05382ae commit 907dc54
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ mod traits_return_impl; // todo: incomplete
mod traits_same_name_fn_call;
mod traits_supertraits;
mod utils;
mod variadic;

// re-exports
use crate::utils::print_type_of;
1 change: 1 addition & 0 deletions src/temp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
// fn ex1_ww() {
// assert_eq!(32, 32);
// }

55 changes: 55 additions & 0 deletions src/variadic.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@

/*
//// C++ variadic template sum
#include <iostream>
// C++17
template<typename... Args>
auto sum(Args... args)
{
return (args + ...);
}
int main() {
std::cout << sum(1, 4.5) << std::endl;; // 5.5 !! // diff. types
std::cout << sum(1, 4, 6) << std::endl;;
return 0;
}
*/

use std::fmt::Debug;

struct Number { x: i32 }
struct Text { y: String }

enum Color {
Num(Number),
Txt(Text)
}

fn variadic_generic(args: &[impl Debug]) {
for arg in args { println!("arg: {:?}", arg); }
}

fn variadic(args: &[Color]) {
if let Color::Num(n) = &args[0] {
println!("n.x: {:?}", n.x);
};
if let Color::Txt(t) = &args[1] {
println!("t.y: {:?}", t.y);
};
}

#[test]
fn ex1() {
variadic(&[
Color::Num( Number{ x: 42 } ),
Color::Txt( Text{ y:"green".to_string() } )
]);

variadic_generic(&[1, 2, 3]);
variadic_generic(&['a', 'b']);

assert_eq!(32, 32);
}

0 comments on commit 907dc54

Please sign in to comment.