Câu hỏi phỏng vấn Rust
Câu hỏi

Is it possible to create a Rust function with default arguments?

Câu trả lời

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:

Using Option Type

You can define a function that takes Option parameters and then provide default values if None is passed.

rust Copy
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"
}

Using Structs with Default Values

Another approach is to use a struct with default values and then pass an instance of this struct to the function.

rust Copy
#[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

middle

Gợi ý câu hỏi phỏng vấn

middle

Does Rust support OOP?

junior

What is the Option type in Rust, and why is it useful?

middle

When can’t my type be Copy in Rust?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào