Return types

Calling a function is an expression, which means it produces a resulting value. We've been ignoring that until now. If a function is going to produce a resulting value, we have to tell the compiler what data type that result will have. We do that like this:

pub fn get(&self) -> i32 {
if self.current < self.min {
return self.min;
}
else if self.current > self.max {
return self.max;
}
else {
return self.current;
};
}

That's a longish example, but for now we're focusing on the first line. After the function parameters, we see ->  i32. That tells Rust that the get function has i32 as the data type of its result. Once it knows that, the compiler will make sure that it's true. In this example, there's no path through the function that doesn't produce an i32 value, so the compiler is happy with it.

We also used the return keyword in that example. A return statement stops the currently running function (meaning that any instructions that would have run after the return statement do not in fact get run) and provides the resulting value for the function call expression. In this example, if the current value is less than the minimum value, the minimum value is returned. If the current value is greater than the maximum value, the maximum value is returned. Otherwise, the current value is returned.

You may recall that in Rust, function bodies are block expressions, and if along with its riders is also an expression, which means they all produce a resulting value naturally, even when we don't use the return keyword. That means that we could have written the example function this way and gotten the same result:

pub fn alternate_get(&self) -> i32 {
if self.current < self.min {
self.min
}
else if self.current > self.max {
self.max
}
else {
self.current
}
}

Do you see the difference? Before, we used return to specifically terminate the function and provide a resulting value. Here, the resulting value of the function's block expression is the resulting value of the if expression, which is the resulting value of the block expression for whichever branch it follows, which is either self.min, self.max or self.current. The end result is the same, but it's expressed differently.

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

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