Parameters
- Rust course
- Beginner
- Lesson 31/115
- 4 min
Learn function parameters and their types.
Parameters
Parameter types are always written explicitly; the compiler doesn't infer types in function signatures. This makes the signature a readable contract on its own:
fn alan(en: f64, boy: f64) -> f64 {
en * boy
}
fn tekrarla(metin: &str, kez: usize) {
for _ in 0..kez {
println!("{metin}");
}
}Are arguments copied?
Small types such as i32, f64 and bool are copied when passed as arguments. Heap types such as String and Vec are moved: the function becomes their owner and the caller can no longer use them. To avoid that, a reference (&String, &str) is passed; you'll see the details in the ownership lesson.
Practice Repeat
Write the fn tekrarla(metin: &str, kez: usize) function; it prints the text kez times on one line separated by spaces (print! + println!() at the end). Call tekrarla("go", 3).
Starter code
fn main() {
// buraya yaz
}Sample solution
fn tekrarla(metin: &str, kez: usize) {
for _ in 0..kez {
print!("{metin} ");
}
println!();
}
fn main() {
tekrarla("go", 3);
}Expected output
go go go
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why doesn't <code>fn ikiye(n) -> i32 { n * 2 }</code> compile?
- The parameter type is missing Correct answer
- The return type is wrong
- return is missing
- It compiles
Explanation: Function parameters need a type annotation: fn ikiye(n: i32) -> i32. Without return, the last expression is the return value.
2 Parameter type
fn kup(n: ____) -> i64 {
n * n * n
}
fn kup(n: i64) -> i64 {
n * n * n
}
Explanation: The parameter type is written after the colon and is required.
3 Signature and meaning
| Term | Meaning |
|---|---|
fn f(a: i32, b: i32) |
Two i32 parameters |
fn f(s: &str) |
Borrowed text |
fn f(s: String) |
Takes ownership |
fn f() -> f64 |
No parameters, returns f64 |