Calling a function

Hi there....
this code id ok:

fn echo()
{
    println!("Hi");
}

fn main() 
{
    echo();
}

Easy, and i get my "Hi".... but this

fn echo()
{
    println!("Hi");
}

fn main() 
{
    echo;
}

compiles with a warrning
warning: path statement with no effect
and i get nothing at runtime. I thing this is a strange behaviour...
Any idea?
Thx

Why so? You're not doing anything with function in the second case - you just have a statement containing its name, that's all.

1 Like

Ok, strange for me. Fox example C# compiler doesn't accept that kind of code.

It's because echo without parenthesises is a value of type function pointer, so it's like writing

5;

which also does not do anything.

1 Like

Ah ok.... that's the point.
thx.

In C#, the language's syntax is defined so that every statement (thing which ends in a semicolon) needs to be a function call, increment/decrement, assignment, or an empty statement. On the other hand, in Rust every statement just needs to be an expression (something which evaluates to a value).

In this case, the echo in echo; is an expression that references the echo function.

1 Like

The word 'echo' is a function. If you put it without the () the you just get the function.

You can pass functions around like any other value.

If you put () parens after a value, then you execute the function the value points to.

fn echo() {
    println!("Hi");
}

fn main() {
    let x = echo;
    x();
}

…to expand on that: so this behavior is nice because if mentioning the name of the function would always call it automatically, then there would be no way to just pass the function itself around when that's what is needed.

1 Like