RUST部分问题

305 阅读1分钟

虽然rust有保姆级的错误提示,但是作为新入门的小白来说,仍有很多问题看着不得要领,在这里浅浅的记录一下吧。

missing field xxxx in initializer of xxxx

这个问题看下函数的返回中是否缺失

pub struct A {
    pub a,
    pub b,
}

impl A {
    pub fn new() -> Self {
    
    ````
        A{
            // 这里和定义的结构不一致时就会提示missing
            a,
            b,
        }
    }
}

cannot find function xxxx in this scope

这个问题出现的范围比较广,是因为rust找不到对应的函数,可能是没有定义,大部分情况可能是没有表明具体的所属,rust会给出修改的建议。

error[E0425]: cannot find function `b` in this scope
  --> src/test.rs:18:30
   |
18 |             a : (b),
   |                  ^ not found in this scope
   |
help: consider using the associated function
   |
18 |             a : (Self::b),
   |                  ++++++

borrow of moved value

这个问题情况挺多,这先记一下Vec的问题

    let mut a = vec![1,2,3]; 
    for x in a{ 
        print!("{},",x); 
    } 
    a[0] += 1;

这样子的话a[0] += 1这里就会报错,因为有个into_iter的隐式调用

其实仔细看一下提示信息的话还是有提示的

`a` moved due to this implicit call to `.into_iter()` | help: consider borrowing to avoid moving into the for loop: `&a` ...

然后改的话就像这样就可以了

    let mut a = vec![1,2,3]; 
    for x in &a { 
        print!("{},",x); 
    } 
    a[0] += 1;