Defining a function

In Rust, a function starts off with the fn keyword. A keyword is a sequence of letters or symbols which has a fixed meaning in the language. Nothing we do in our program can change the meaning of a keyword, and the libraries we use can't change the meaning either. Keywords occasionally have different meaning in clearly different contexts, but they always mean the same thing when used in the same way. Keywords are the solid foundation that everything else is built on.

So, the fn keyword is used to tell the Rust compiler that we're about to tell it about a new function. After that, separated by a space, comes the function's name. There are rules for what the function name can look like:

  • It must be made up of the following:
    •  English letters (the letters A through Z, in their lowercase or CAPITAL forms)
    • Arabic numerals (the digits 0 through 9)
    • Underscores(_)
  • It can't start with a number (so 7samurai is not a valid name)
  • If it starts with an underscore, it must have at least one further character (_ by itself has a special meaning)

Then comes an open parenthesis ( and a close parenthesis ), with a list of parameters between them. We're going to gloss over the parameter list for now and come back to that later. There doesn't have to be anything between the parenthesis if the function does not need parameters, and that's how we'll do it for now.

After the close parenthesis of the parameter list, we can optionally include a  symbol followed by a return type, another thing which we'll go into in more detail later.

Next comes a { symbol, which tells Rust that we're about to begin a sequence of commands, followed by as many commands as we need in order to tell Rust how to do what we want the function to do, and then finally a } symbol to mark the end.

Going back to the boilerplate code, Let's take a look at the automatically generated main function again:

fn main() {
println!("Hello, world!");
}

Here, we can see the fn keyword, function name, and empty parameter list. The optional return type has been omitted. Then, between the { and }, we see a single instruction, which tells the computer that we want it to print out Hello, world! whenever we tell it to run the main function.

There's not a lot more to say about functions until we have some understanding of what kinds of instructions we can give the computer, between those { and } symbols. The main idea is that we can bundle up many instructions into a function, and then use a single instruction elsewhere in the program to tell the computer to do all that stuff.

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

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