No elegant way to iterate over linked list in C-style loop? #26785
Replies: 1 comment
-
|
Because V emphasizes safety and explicit error/none handling, the traditional C-style iteration is restricted to prevent unintentional access to Comparison of Approaches
Recommendation: Iterator InterfaceThe most idiomatic "V-way" is to implement the Iterator Interface. By defining a ImplementationTo make your pub struct List {
pub mut:
front ?&ListNode
back ?&ListNode
}
pub struct ListNode {
pub mut:
val int
prev ?&ListNode
next ?&ListNode
}
// 1. Define the iterator state
struct ListIter {
mut:
curr ?&ListNode
}
// 2. Implement the next() method
// V recognizes any type with this signature as an iterator
fn (mut it ListIter) next() ?&ListNode {
node := it.curr? // Returns none if curr is none, ending the loop
it.curr = node.next
return node
}
// 3. Helper method to start iteration
fn (l &List) iter() ListIter {
return ListIter{ curr: l.front }
}
fn main() {
// Example usage
mut list := &List{
front: &ListNode{ val: 1, next: &ListNode{ val: 2 } }
}
// Now you can use the elegant for-in syntax
for node in list.iter() {
println(node.val)
}
}Tip Using Does your specific use case require modifying the |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Beta Was this translation helpful? Give feedback.
All reactions