Is it possible to create a Rust function with default arguments?
Is it possible to create a Rust function with default arguments?
In Rust, it is not possible to directly create a function with default arguments in the same way you might in languages like Python or C++. However, you can achieve similar functionality using optional parameters with the Option
type or by using structs with default values. Here are a couple of approaches to simulate default arguments in Rust:
Option
TypeYou can define a function that takes Option
parameters and then provide default values if None
is passed.
fn example_function(param1: Option<i32>, param2: Option<&str>) {
let param1 = param1.unwrap_or(10); // Default value for param1 is 10
let param2 = param2.unwrap_or("default"); // Default value for param2 is "default"
println!("param1: {}, param2: {}", param1, param2);
}
fn main() {
example_function(Some(5), None); // param1 = 5, param2 = "default"
example_function(None, Some("custom")); // param1 = 10, param2 = "custom"
example_function(None, None); // param1 = 10, param2 = "default"
}
Another approach is to use a struct with default values and then pass an instance of this struct to the function.
#[derive(Default)]
struct Params {
param1: i32,
param2: String,
}
fn example_function(params: Params) {
println!("param1: {}, param2: {}", params.param1, params.param2);
}
fn main() {
let default_params = Para...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào