i32 { let mut w-6ren">
gpt4 book ai didi

rust - "Cannot infer type - type annotations needed",但类型已知

转载 作者:行者123 更新时间:2023-12-05 05:54:10 26 4
gpt4 key购买 nike

我一直在 LC 上练习,我打了 following issue .

pub fn largest_rectangle_area(heights: Vec<i32>) -> i32 {
let mut widths = vec![(0usize, heights.len()); heights.len()];
let mut stack = vec![];

for (idx, &x) in heights.iter().enumerate() {
while let Some(&pos) = stack.last() {
if x >= heights[pos] {
break;
}

widths[pos].1 = idx;
stack.pop();
}

stack.push(idx);
}

todo!()
}

error[E0282]: type annotations needed
--> src/lib.rs:11:13
|
11 | widths[pos].1 = idx;
| ^^^^^^^^^^^ cannot infer type
|
= note: type must be known at this point

更奇怪的是,如果我先执行 widths[pos] = (0, idx);then the error disappears :

pub fn largest_rectangle_area(heights: Vec<i32>) -> i32 {
let mut widths = vec![(0, heights.len()); heights.len()];
let mut stack = vec![];

for (idx, &x) in heights.iter().enumerate() {
while let Some(&pos) = stack.last() {
if x >= heights[pos] {
break;
}

widths[pos] = (0, idx); // do a full update
stack.pop();
}

stack.push(idx);
}
stack.clear();

for (idx, &x) in heights.iter().enumerate().rev() {
while let Some(&pos) = stack.last() {
if x >= heights[pos] {
break;
}

widths[pos].0 = idx + 1; // now it's fine to use `.0`
stack.pop();
}

stack.push(idx);
}
todo!()
}

我是不是遗漏了什么,或者这是编译器中的错误?

更新

@ Ömer Erden发现,它无法推断出应该是 usizepos 类型,因为它间接来自 enumerate()

这看起来很奇怪,因为它在执行 widths[pos].1 = idx; 时无法推断出 pos 的类型,但在执行 widths 时却成功了[pos] = (0, idx);

He also managed to create more minimal MCVE:

fn _some_fn() {
let mut widths = vec![(0usize, 0usize); 100];
let mut stack = vec![];
//let mut stack:Vec<usize> = vec![]; //why explicit type definition needed

let a = stack.pop().unwrap();
let idx = 0usize;
widths[a].1 = idx;

stack.push(idx);
}

错误报告

https://github.com/rust-lang/rust/issues/90252

最佳答案

我不知道为什么编译器无法省略类型,但您可以通过一些简单的更改手动注释它:

pub fn largest_rectangle_area(heights: Vec<i32>) -> i32 {
let mut widths = vec![(0usize, heights.len()); heights.len()];
let mut stack = vec![];

for (idx, &x) in heights.iter().enumerate() {
while let Some(&pos) = stack.last() {
if x >= heights[pos] {
break;
}
let at_pos: &mut (usize, usize) = &mut widths[pos];
at_pos.1 = idx;
stack.pop();
}

stack.push(idx);
}

todo!()
}

Playground

关于rust - "Cannot infer type - type annotations needed",但类型已知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69696784/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com