This repository is a Rust Foundation experiment in ergonomic function overloading in Rust.
The experiment uses macros to improve the ergonomics of the
splat Rust language experiment. Technical details for the current stage of the
experiment can be found on the Inside Rust blog.
Most of this code requires a recent nightly Rust compiler.
Contributions to this project are welcome, as long as you follow the Code of Conduct. See the developer setup instructions below for details.
AI usage must be disclosed. Do not use AI for GitHub descriptions or comments. Write in your native language, or in English. You can use LLMs to answer questions, analyze, check, and review. But not to create code. See the full LLM Policy for details.
Some outcomes of this experiment are summarised in the C++ overloads in Rust document & compatibility table.
These outcomes are based on the current state of the experimental compiler feature and overloading macro: they are not Rust language design decisions.
Install a recent version of the nightly Rust compiler, and use it to build your project.
Add this overloading-macros crate as a dependency.
rustup update nightly
cd your-project-name
rustup override set nightly
cargo add overloading-macros || \
cargo add --git https://github.com/rustfoundation/overloading-macros overloading-macrosThen use the macro to add overloading to your functions or methods.
#![feature(splat, tuple_trait)]
#![allow(incomplete_features, unused_braces)]
use splat_overload::overload;
// Functions can be overloaded
overload! {
fn show(num: i32) { println!("num: {}", num); }
fn show(nums: Vec<i32>) { println!("nums: {:?}", nums); }
}
struct Example;
// So can methods and return values
overload! {
impl Example {
fn tell(&self, num: i32) -> i32 { println!("num: {}", num); return num; }
fn tell(&self, nums: Vec<i32>) -> Vec<i32> { println!("nums: {:?}", nums); return nums; }
}
}
fn main() {
show(42);
show(vec![42, 43, 44]);
let e = Example;
let _num = e.tell(42);
let _nums = e.tell(vec![42, 43, 44]);
}PRs are welcome, particularly to:
- improve the macro's ergonomics
- document how to import overloads into other modules
- fix bugs in this experimental macro
rustup update nightly
git clone https://github.com/rustfoundation/overloading-macros
cd overloading-macros
rustup override set nightly
cargo buildRun individual example binaries with:
cargo run --bin <filename>For example:
cargo run --bin multiple-argsSometimes the C++ code extracted by cpp_build will become outdated, and you will get errors like:
error: This cpp! macro is not found in the library's rust-cpp metadata.
NOTE: Only cpp! macros found directly in the program source will be parsed -
NOTE: They cannot be generated by macro expansion.
...
error: cannot find macro `__cpp_closure_impl` in this scope
To fix these errors, run cargo clean then rebuild.
If the errors still happen after a clean, check your Rust and C++ code is compiling correctly.