Ben Chuanlong Du's Blog

It is never too late to learn.

Function in Rust

In [ ]:
:timing
:sccache 1

Tips

  1. Functions in a module is private by default. To make it public (so that it can called outside the module), you have to use the keyword pub.
In [18]:
fn add1(x: i32, y: i32) -> i32 {
    x + y
}
In [19]:
add1(1, 2)
Out[19]:
3
In [21]:
let add2 = |x: i32, y: i32| x + y; 
add2(1, 2)
Sorry, the type [closure@src/lib.rs:112:12: 112:34] cannot currently be persisted

Function Overload

Rust does not support function overloading. There are multiple alternative ways to the OOP-style function overloading in Rust.

  1. Simply define different methods.
  2. Use trait to simulation function overloading.

Is there a simple way to overload functions?

Default/Optional Arguments

Rust does not support optinal arguments for Functions. For more discussions, please refer to Optional arguments in Rust .

In [ ]:

Comments