Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call the function when a variable and function have a same name?

Tags:

rust

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.

like image 206
hzqelf Avatar asked Dec 16 '19 08:12

hzqelf


People also ask

Can a function and variable have the same name?

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.

Can 2 function have same name?

Yes, it's called function overloading. Multiple functions are able to have the same name if you like, however MUST have different parameters.

What is the preference given if a function and variable has same name?

if function name and variable name are same then JS Engine ignores the variable.

Can function have same name?

That is, you can use the same name for two or more functions in the same program.


1 Answers

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());
}
like image 100
Denys Séguret Avatar answered Sep 27 '22 20:09

Denys Séguret