Passing by value

The following code shows how to pass a number between two functions, and to receive a result:

fn main() 
{ 
    let add = add_values(3, 5);  
    println!("{:?}", add); 
} 
 
fn add_values(a: i32, b: i32) -> i32 
{ 
    a + b 
} 

Let's have a look at the receiving function's definition line:

fn add_values(a: i32, b: i32) -> i32 

As with any programming language, we have to give the function a name, and then a parameter list. The parameter names are followed by a colon and the type of the parameter.

Our function returns a value (this is signified by the -> symbol) of a particular type (in this case, i32). The last evaluated thing in the function will be returned from the function, provided that you don't accidentally put a semi-colon there. An implicit return statement also exists, but it's not required and it's usually better style to omit it if possible.

When built and run, you will see the following:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset