FallenWarrior
FallenWarrior

Reputation: 686

Which method of getting a reference to a struct field is the preferred way?

I've been overwhelmed by all the ways to get a reference to a struct field from a reference to a struct. These are the ways I'm aware of right now:

struct Foo {
    bar: i32,
}

let foo = &Foo { bar: 123 };

let bar1 = &foo.bar;
let ref bar2 = foo.bar;
let ref bar3 = (*foo).bar;
let &Foo { bar: ref bar4 } = foo;
let Foo { bar: bar5 } = foo;
let Foo { bar: ref bar6 } = foo;
let Foo { bar: ref bar7 } = *foo;

Which of these is the "preferred way"? I assume that field access like foo.bar is preferred for a single field and pattern matching for getting multiple ones in one go, but it's unclear to me which of the multiple ways I've listed above I should use for each case.

Upvotes: 0

Views: 77

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382264

There's no reason to avoid the direct access which would be

let bar1 = &foo.bar;

This is easier to write and to read. You don't need pattern matching here.

Pattern matching is an additional tool, which basically solves two kinds of problems:

  • destructure a value into several ones, for example let (a, b) = c;
  • being conditional ("refutable") in a while let, if let, match arm

See All the places patterns can be used.

Some of your declarations are officially discouraged. Clippy would warn you about the ref ones.

Upvotes: 5

Related Questions