A simple qustion regarding reference

I am going through "rust by practice", here is my quesiton
Are ref or & same when get a reference?

let c = '中';  
let r1 = &c;
let ref r2 = c;
let c = '中';  
let r1 = &c;
let r2 = &c;

Yes, let ref r2 = c; and let r2 = &c; do the same thing. The latter (using &) is more idiomatic, while ref can be useful as part of a more complicated pattern e. g. in a match.

1 Like

Strictly speaking, ref in the pattern (i.e. on the left side of let, before the arrow in the match arm, in the function signature, etc.) is the same as & in the value, while & in the pattern roughly corresponds to dereferencing of the value.

2 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.