我在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发布于 2021-02-11 03:55:20
@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数组,这样就不必为此而烦恼了
发布于 2021-01-23 12:06:22
免责声明,这是我在V lang的第二天...
添加到stack.v之后,我又多了一步,这只是我在这个场景中使用的主.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个小时,如果头脑清醒,我会做得更好……
https://stackoverflow.com/questions/65822781
复制相似问题