A variable and function have the same name. How do I call the function?
fn main() {
let a = 1;
fn a() -> i32 {
2
}
println!("{}", a());
}
The Rust compiler told me:
error[E0618]: expected function, found `{integer}`
In other words, the Rust compiler does not call the a
function, but instead accesses the a
variable.
Conflicts with Function NamesAvoid creating variables with the same name as a function (such as i , j , mode , char , size , and path ). In general, variable names take precedence over function names. If you create a variable that uses the name of a function, you sometimes get unexpected results.
Yes, it's called function overloading. Multiple functions are able to have the same name if you like, however MUST have different parameters.
if function name and variable name are same then JS Engine ignores the variable.
That is, you can use the same name for two or more functions in the same program.
This can't be done because you don't have both the function and the integer in scope where you have your println
.
Because functions are normally available for the entire scope (i.e. you can use them before their declaration), their declaration is conceptually moved to the start of the scope (they're "hoisted").
A consequence is that the function declaration is before the integer variable declaration and is shadowed.
The real fix of your code would depend on your exact situation. Maybe something like this:
fn main() {
{
let a = 1;
// use the integer there
}
fn a() -> i32 {
2
}
println!("{}", a());
}
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