Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the order of function arguments evaluation and structs initialization in Rust?

Tags:

rust

Is the order of function argument evaluation defined in Rust?

fn f(a: u64, b: u64, c: u64) {}
fn g() -> u64 { 0 }
fn h() -> u64 { 1 }
fn i() -> u64 { 2 }

fn main() {
    f(g(), h(), i());
}

Also, I am worried about the initialization order of structs:

fn f() {}
fn g() {}

A {
    a: f(),
    b: g(),
}

Is the order guaranteed to be a and then b?

For my particular use case, I am going to initialize a struct within a diesel transaction like that:

db_connection.transaction(||
    Ok(CompanyAndUser {
        company: companies::register_company(...)?, // performs diesel insert
        user: users::register_user(...)?, // performs diesel insert
    })
);

Obviously, I want these two diesel calls within a transaction to be ordered. I have not found any information about this, unfortunately. Also, I've found some more or less relevant info, but it was quite old.

like image 919
Victor Polevoy Avatar asked Aug 22 '19 14:08

Victor Polevoy


People also ask

Does the order matter when passing arguments to a function?

Yes, it matters. The arguments must be given in the order the function expects them. C passes arguments by value. It has no way of associating a value with an argument other than by position.

What are rust functions?

Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code.

What does -> mean in Rust?

It means the function never returns (usually because it unconditionally panics or otherwise ends the program, or because it contains an infinite loop that prevents a return from ever happening). The appendix describes it as: ! Always empty bottom type for diverging functions.

How do you create a function in Rust?

We define a function in Rust by entering fn followed by a function name and a set of parentheses. The curly brackets tell the compiler where the function body begins and ends. We can call any function we've defined by entering its name followed by a set of parentheses.


1 Answers

The order used to be unspecified, but it's now left-to-right:

Many expressions contain sub-expressions, called the operands of the expression.

and:

The operands of these expressions are evaluated prior to applying the effects of the expression. Expressions taking multiple operands are evaluated left to right as written in the source code.

like image 98
Boiethios Avatar answered Oct 22 '22 08:10

Boiethios