Source file test/closure_dynconst.go

     1  // run
     2  
     3  // Copyright 2026 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  // Test that a closure that captures a variable holding a constant still
     8  // observes the right value once inlining made several copies of it, each
     9  // capturing a different constant.
    10  
    11  package main
    12  
    13  import "fmt"
    14  
    15  func str(s string) func() string {
    16  	return func() string { return s }
    17  }
    18  
    19  func num(n int) func() int {
    20  	return func() int { return n }
    21  }
    22  
    23  func iface(n int) func() any {
    24  	return func() any { return n }
    25  }
    26  
    27  func nested(s string) func() func() string {
    28  	return func() func() string {
    29  		return func() string { return s }
    30  	}
    31  }
    32  
    33  func main() {
    34  	for i, f := range []func() string{str("a"), str("b"), str("c")} {
    35  		if got, want := f(), string(rune('a'+i)); got != want {
    36  			panic(fmt.Sprintf("str: got %q, want %q", got, want))
    37  		}
    38  	}
    39  
    40  	for i, f := range []func() int{num(0), num(1), num(2)} {
    41  		if got := f(); got != i {
    42  			panic(fmt.Sprintf("num: got %d, want %d", got, i))
    43  		}
    44  	}
    45  
    46  	for i, f := range []func() any{iface(0), iface(1), iface(2)} {
    47  		if got := f(); got != any(i) {
    48  			panic(fmt.Sprintf("iface: got %v, want %v", got, i))
    49  		}
    50  	}
    51  
    52  	for i, f := range []func() func() string{nested("a"), nested("b"), nested("c")} {
    53  		if got, want := f()(), string(rune('a'+i)); got != want {
    54  			panic(fmt.Sprintf("nested: got %q, want %q", got, want))
    55  		}
    56  	}
    57  }
    58  

View as plain text