Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to set a default value to function parameters in Rust

2 Answers

0 votes
// In Rust, you can't set default values for function parameters.
// However, you can achieve a similar effect using optional parameters with the Option type.

fn my_function(param: Option<i32>) {
    let param = param.unwrap_or(-1);
    
    println!("param: {}", param);
}

fn main() {
    my_function(Some(100)); 
    
    my_function(None);     
}

 
 
 
   
/*
run:
   
param: 100
param: -1
  
*/

 



answered Jan 28, 2025 by avibootz
0 votes
// In Rust, you can't set default values for function parameters.

// Another approach is to use function overloading by defining multiple versions 
// of the function, each with a different number of parameters

fn my_function(param: i32) {
    println!("param: {}", param);
}

fn my_function_with_default() {
    my_function(-1);
}

fn main() {
    my_function(100);         
    my_function_with_default(); 
}

 
 
   
/*
run:
   
param: 100
param: -1
  
*/

 



answered Jan 28, 2025 by avibootz

Related questions

1 answer 89 views
1 answer 92 views
1 answer 73 views
1 answer 92 views
2 answers 88 views
1 answer 90 views
1 answer 69 views
...