结构体必须有一个 `next()` 方法才能成为迭代器

问题描述

我在 vlang 中遇到此错误

a struct must have a next() method to be an iterator

struct Items {
    item []Item
}

struct Item {
    name string
    link string
  tags []string
}
pub fn (mut app App) index() vweb.Result {
    text := os.read_file(app.db) or { panic(err) }
    items := json.decode(Items,text) or { panic(err) }
    println(items)
    return $vweb.html()
}

index.html:

@for item in items
    <h2>@item.name</h2>
@end

解决方法

免责声明,这是我在 V lang 的第二天...

将此添加到 stack.v 后,我又向前迈进了 1 步,这只是我针对此场景的主要 .v 文件

也许你的理解足以让你继续踏出这一步?

pub fn (i &Items) next() Item {
  return i.name
} 

它停止抱怨a struct must have a next() method to be an iterator

并开始抱怨返回类型并坚持可选。

我能走到这一步要归功于:V Docs:References V Docs: Heap Structs V Docs: Methods V lib: Method Args

我期待听到这是否让您有所收获,明天我会继续关注这个,因为我想要理解它。但是我现在已经连续 13 小时了,而且我会在头脑清醒的情况下做得更好......

,

@DeftconDelta 正在寻找正确的方向?

您需要定义一个名为 next 的方法,该方法返回一个可选值(即返回以 ? 开头的类型,例如 ?int

因此,对于您来说,此方法类似于以下内容:

// You need to include a pointer to the current item in your struct
struct Items {
    items       []Item
    current_idx int = -1
}

pub fn (mut i Items) next() ?Item {
    i.current_idx++
    if i.current_idx >= i.items.len {
        // tell the iterator that there are no more items
        return none
    }
    return i.items[i.current_idx]
}

否则,如果结构不是真的需要,你可以只使用Item的数组,这样你就不必费心了?