7

In the Bevy book the following code is used:

struct GreetTimer(Timer);

fn greet_people(
    time: Res<Time>, mut timer: ResMut<GreetTimer>, query: Query<&Name, With<Person>>) {
    // update our timer with the time elapsed since the last update
    // if that caused the timer to finish, we say hello to everyone
    if timer.0.tick(time.delta()).just_finished() {
        for name in query.iter() {
            println!("hello {}!", name.0);
        }
    }
}

What are the timer.0 and name.0 calls doing? The book doesn't address it, and I see that Timer has a tick method, so what is .0 doing here since timer is already a Timer?

BWStearns
  • 2,567
  • 2
  • 19
  • 33
  • 2
    But you're using `GreetTimer`, not `Timer`. And GreetTimer is a [tuple struct](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#using-tuple-structs-without-named-fields-to-create-different-types), so you have to access its first (and only) element, as `GreetTimer` itself does not define a `tick()` method. – justinas Nov 11 '21 at 20:40

1 Answers1

6

It is related to tuples. In rust tuples can be accessed by item position in that way:

let foo: (u32, u32) = (0, 1);
println!("{}", foo.0);
println!("{}", foo.1);

It also happens with some (tuple) structs:

struct Foo(u32);

let foo = Foo(1);
println!("{}", foo.0);

Playground

You can further check some documentation.

Netwave
  • 40,134
  • 6
  • 50
  • 93
  • So `ResMut` is a 1-tuple of `GreetTimer` or the ResMut struct can be operated upon as if it were a tuple? – BWStearns Nov 11 '21 at 20:40
  • 1
    @BWStearns, GreetTimer is a wrapper type, which its solely inner element is accessed with that `.0` – Netwave Nov 11 '21 at 20:41
  • 2
    `ResMut` [implements](https://docs.rs/bevy/0.5.0/bevy/prelude/struct.ResMut.html#trait-implementations) `Deref` / `DerefMut`, that's why you can magically operate on `ResMut` as if it were a `T` ([see book](https://doc.rust-lang.org/book/ch15-02-deref.html)). `.0` is an artifact of `GreetTimer` being a tuple struct, and is a separate concern from `ResMut` being automatically dereferenced by the compiler. – justinas Nov 11 '21 at 20:44
  • Thanks. This was really helpful! – BWStearns Nov 11 '21 at 20:45