First error encountered


fn main() {
    let mut heap_num = vec![4,5,6];
    let ref1: &Vec<i32> = &heap_num;
    let ref2: &Vec<i32> = &heap_num;
    println!("ref1 : {:?} ,ref2:{:?}",ref1,ref2);
}

error:

 |
3 |     let mut heap_num: &Vec<i32> = vec![4,5,6];
  |                       ---------   ^^^^^^^^^^^ expected `&Vec<i32>`, found struct `Vec`
  |                       |
  |                       expected due to this

expected reference &Vec<i32> found struct Vec<{integer}>=
note: this error originates in the macro vec

--i am following [Nouman from Udemy]

Requesting for help with explanations.
Thanks

Please post code as text, not as image. Images can't be copy-pasted so we can't reproduce the error.

Anyway, the code should work as-is. Don't use IDEs while you are learning the language. They often produce misleading or downright wrong errors. Use cargo build to build your code – that'll use the real compiler of which the output you can trust.

2 Likes

hey thanks for the info there , let me share the code and would online rust official ide is good to start?

bdw i tried online ide that shows same error.

The error you posted doesn't match the code you posted. This code runs fine.

fn main() {
    let mut heap_num = vec![4,5,6];
    let ref1: &Vec<i32> = &heap_num;
    let ref2: &Vec<i32> = &heap_num;
    println!("ref1 : {:?} ,ref2:{:?}",ref1,ref2);
}

However, the line of code in the error is different:

let mut heap_num: &Vec<i32> = vec![4,5,6];

This is invalid because the type of vec![4,5,6] is Vec<i32>, but you have declared the type &Vec<i32> for the variable, which is a different type. To correct it, remove the &.

let mut heap_num: Vec<i32> = vec![4,5,6];
3 Likes

Note Rust references are not the same thing as general-purpose storing/passing by reference in other, garbage-collected programming languages. Rust references can't exist on their own.

A &Type means "a view into a Type stored somewhere else already", like in your example the vec is stored in heap_num, and ref1 is a temporary view into the heap_num's value.

You can't make a brand new object that is a temporary reference type. let heap_num: &Vec<i32> = vec![] doesn't make sense, because it's not borrowing from a value stored somewhere. That vec![] on the right side isn't stored anywhere yet. There is no location to borrow from.

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