Dot Zero call to timer in Rust/Bevy?
Asked Answered
D

1

8

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?

Develop answered 11/11, 2021 at 20:36 Comment(1)
But you're using GreetTimer, not Timer. And GreetTimer is a tuple struct, so you have to access its first (and only) element, as GreetTimer itself does not define a tick() method.Gunny
F
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.

Fyke answered 11/11, 2021 at 20:38 Comment(4)
So ResMut<GreetTimer> is a 1-tuple of GreetTimer or the ResMut struct can be operated upon as if it were a tuple?Develop
@BWStearns, GreetTimer is a wrapper type, which its solely inner element is accessed with that .0Fyke
ResMut implements Deref / DerefMut, that's why you can magically operate on ResMut<T> as if it were a T (see book). .0 is an artifact of GreetTimer being a tuple struct, and is a separate concern from ResMut being automatically dereferenced by the compiler.Gunny
Thanks. This was really helpful!Develop

© 2022 - 2024 — McMap. All rights reserved.