borgo icon indicating copy to clipboard operation
borgo copied to clipboard

Capture in the lambda, causes stack overflow (?)

Open arslanarm opened this issue 1 year ago • 0 comments

Not sure what is the root cause of the issue, but compiling these code leads to stack overflow:

use fmt

struct Iterator<T> {
    next: fn() -> Option<T>
}

fn iter<T>(list: [T]) -> Iterator<T> {
    let mut i: int = 0
    Iterator { 
        next: || {
            if i < list.Len() {
                let x = list[i]
                i = i + 1
                Some(x)
            } else {
                None
            }
        },
    }
}


fn main() {
    let xs = [1, 2, 3, 4, 5]
    fmt.Println(iter(xs))
}

Possible causes:

  1. Because I am trying to mutate i, compiler freaks out
  2. Some ungodly reason that is beyond my comprehension

But, I tried to remove the logic from the lambda, and got following error

fn iter<T>(list: [T]) -> Iterator<T> {
    Iterator { 
        next: || {
            None
        },
    }
}

.\main.go:12:28: cannot use func() (T, bool) {…} (value of type func() (T, bool)) as func() Option[T] value in struct literal when trying to compile the go code.

Here is the snippet from main.go:

type Iterator[T any] struct {
  next func () Option[T]
} 
 func  iter [T any] (list []T) Iterator[T] {


return Iterator[T] { next: func () (T, bool) {



        if make_Option_None[T]().IsSome() {
            return make_Option_None[T]().Some, true
        }
        return *new(T), false
              
},  }  
}

arslanarm avatar May 18 '24 22:05 arslanarm