I don't know whether this is considered to be a good programming practice but personally, I find that calling a function by naming its arguments makes the code more readable. I don't know whether this is possible in Rust programming language. I didn't find any named call expression in the grammar:
https://doc.rust-lang.org/reference/expressions/call-expr.html
So for example the following doesn't compile:
fn add(n1 : i32, n2 : i32) -> i32 {
n1 + n2
}
fn main() {
let sum_value = add(n1 = 124, n2 = 200);
println!("sum = {}", sum_value);
}
Therefore my question is: Is naming arguments in function call is possible in Rust and if the answer is yes, is it considered to be a good practice according to Rust best practices? (I'm a beginner)
Environment:
OS: Linux Ubuntu MATE 20.04.1 (64 bits)
rustc --version: rustc 1.46.0 (04488afe3 2020-08-24)
Therefore my question is: Is naming arguments in function call is possible in Rust
Rust does not support named parameters as part of the language.
is it considered to be a good practice according to Rust best practices? (I'm a beginner)
Generally not (the rather strong typing usually helps mitigate this issue)
In cases where it really is useful two patterns crop up repeatedly:
See the article linked to https://old.reddit.com/r/rust/comments/fg6vrn/for_your_consideration_an_alternative_to_the/ for more information (I'm linking to the thread because there is useful discussion of the options, as well as links to helpful crates).
No, there are no named/keyword parameters in Rust. They have been discussed for a long time, but there are no concrete plans to add them.
If you have many parameters in a function, consider passing a struct, the builder pattern, etc.
By the way: the add()
example does not show why named/keyword parameters could be useful, since the parameters are interchangeable.
There is an RFC open on this topic.
Although not everyone in this RFC agrees, it seems that there is generally support for adding named and default parameters to Rust (including support from the core team). It seems the primary obstacle is not in the concept, but in the implementation.
As noted in the RFC, alternatives (such as the builder pattern) have the same issues as built-in named and default parameters, but also add large amounts of boilerplate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With