somenickname
somenickname

Reputation: 619

expected identifier, found `=` when referencing a vector

In the Rust official doc, there is a code sample as:

fn main() {
    let number_list = vec![34, 50, 25, 100, 65];

    let result = largest(&number_list);
    println!("The largest number is {}", result);

    let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];

    let result = largest(&number_list);
    println!("The largest number is {}", result);
}

I was wondering what &number_list looks like (is it the same as &number_list[0]), so I tried this example:

fn reference() {
    let number_list = vec![1,2,3,4,5];
    let ref = &number_list;
    println!("{}", ref);
}

However, I got the error:

error: expected identifier, found `=`
   |
   |     let ref = &number_list;
   |             ^ expected identifier

Any clues on this? Why is it not assign-able and gives an error message that doesn't quite make sense (at least for me)?

Upvotes: 0

Views: 318

Answers (4)

Miiao
Miiao

Reputation: 998

As others said, ref is a keyword in Rust. But if you wanna use it that much, you can use ref pattern:

fn reference() {
    let number_list = vec![1,2,3,4,5];
    let ref my_ref = &number_list;
    println!("{:?}", my_ref);
}

And no, &idxable isn’t &idxable[0], it’s exactly &idxable.

You don’t need vectors in this example by the way.

Upvotes: 0

9bO3av5fw5
9bO3av5fw5

Reputation: 998

ref is a keyword

try:

fn reference() {
    let number_list = vec![1,2,3,4,5];
    let my_variable = &number_list;
    println!("{}", my_variable);
}

Upvotes: 3

Silvio Mayolo
Silvio Mayolo

Reputation: 70267

ref is a Rust keyword.

ref annotates pattern bindings to make them borrow rather than move. It is not a part of the pattern as far as matching is concerned: it does not affect whether a value is matched, only how it is matched.

Upvotes: 2

Matias Bertoni
Matias Bertoni

Reputation: 498

ref is a keyword. Try adding another name to the variable

Upvotes: 0

Related Questions