Skip to content

defer not working correctly from loops #14701

Description

@emdete

OS: linux, Devuan GNU/Linux 5 (daedalus/ceres)
Processor: 8 cpus, 64bit, little endian, Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
CC version: cc (Debian 11.3.0-3) 11.3.0

What did you do?

fn f(k int){
	eprintln(k)
}

fn main() {
	mut i := 0
	for i<10 {
		i++
		defer{f(i)}
	}
}

What did you expect to see?

output of 10 lines

What did you see instead?

only one line, the defer is executed once only.

this is the similar code in go:

package main
import "log"

func main() {
	i := 0
	for i<10{
		defer log.Printf("close %d", i)
		i += 1
	}
	log.Printf("done")
}

which works as expected.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugThis tag is applied to issues which reports bugs.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions