Impl methods on tuple struct

Hi,

im trying to increment a tuple struct field by 2 as below with impl method on tuple struct.

struct Foo(i32);
 impl Foo{
     fn plus2(v: &Foo) -> Foo {
                return Foo(*v.0 + 2);
        }
}

fn main()
{
        let x = Foo(2);
        let y = Foo::plus2(&x);
        println!( "{} {}" , x.0, y.0);
}

It throws the following error:

error[E0614]****: type `i32` cannot be dereferenced**
 tuple_struct.rs:8:10
 return Foo(*v.0 + 2);
**|******.  **^^^^**

What am I doing wrong? I am assuming *v would dereference the tuple reference and then .0 would access the 0th field.

No, you've got the precedences backwards. Postfix operations bind stronger than prefix ones. *v.0 is *(v.0). What you meant is (*v).0, but since field access auto-dereferences if needed, you can just write v.0.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.