Rust function with parameter (&str)
-
&str
-
Functions can expect parameters.
-
We have to define the type of the parameter.
-
In this case we are expecting a string slice
&str
. -
If we already have a string slice we can pass it as it is.
-
If we have a String then we have to prefix it with
&
.
fn main() { greet("Foo"); greet("Bar"); println!(); let name = "Foo"; greet(name); greet(name); println!(); let name = String::from("Bar"); greet(&name); greet(&name); } fn greet(name: &str) { println!("Hello {}!", name); }
Hello Foo!
Hello Bar!
Hello Foo!
Hello Foo!
Hello Bar!
Hello Bar!