expected identifier, found `=` when referencing a vector

expected identifier, found `=` when referencing a vector

Problem Description:

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)?

Solution – 1

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

Solution – 2

ref is a keyword

try:

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

Solution – 3

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.

Solution – 4

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.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject