Hello Functions

Let's go back to our hello name example, but this time create a function to do the greeting. In Perl it might look like this.

#!/usr/bin/env perl

use v5.28;
use warnings;

greet("Tim");

sub greet {
    my $name = shift;
    say "Hello, $name!";
}

The same thing in Rust might look like this.

fn main() {
    greet("Tim");
}

fn greet(name: &str) {
    println!("Hello, {}!", name);
}

Here we see the type of the parameter that must be passed to greet in the function signature. Perl's subroutine signatures are still experimental, but if we use those then the two examples look more similar.

#!/usr/bin/env perl

use v5.28;
use warnings;
use experimental qw(signatures);

greet("Tim");

sub greet($name) {
    say "Hello, $name!";
}

Here we see the Perl subroutine greet takes a single scalar as a parameter. The Rust function greet takes a single parameter also, but it must be a string slice (&str). No other type will do.

In Perl, we could add

greet("Tim");
greet(3);

and it would print

Hello, Tim!
Hello, 3!

In Rust, it wouldn't compile.

error[E0308]: mismatched types
 --> src/main.rs:3:11
  |
3 |     greet(3);
  |           ^ expected `&str`, found integer

We would have to first convert the integer to a string slice.

fn main() {
greet("Tim");
greet(&3.to_string());
}

fn greet(name: &str) {
   println!("Hello, {}!", name);
}

There's a tiny bit of magic here as we've actually passed it a reference to a string (&String) not a string slice (&str), but an entire string counts as a slice, so it's okay.

Hello, Tim!
Hello, 3!

There's an analogous situation with Rust's arrays, vectors, and slices.