1 // A function parameter is MUTABLE: a callee may write through a parameter
2 // pointer and may assign to a parameter, and the caller sees the write. Named
3 // results are required and are assignable like locals.
4 //
5 // Pinned because the memory model claimed the opposite for a long time
6 // ("parameters are immutable borrows, writing through a parameter pointer is a
7 // compile-time error") while neither compiler enforced it and 570 sites in the
8 // tree already relied on mutability. Round 296 made the model say what the
9 // compilers do.
10 package main
11 12 type pair struct {
13 a int32
14 b int32
15 }
16 17 func fill(p *pair, n int32) (seen int32) {
18 p.a = n
19 p.b = p.a * 2
20 seen = p.a + p.b
21 return
22 }
23 24 func bump(n int32) (out int32) {
25 n = n + 1
26 out = n * 10
27 return
28 }
29 30 func main() {
31 // Termination: a batch program must still be stoppable, so the entry
32 // handles the channel the runtime closes on SIGINT/SIGTERM.
33 select {
34 case <-shutdown:
35 return
36 default:
37 }
38 39 var p pair
40 seen := fill(&p, 7)
41 if p.a != 7 {
42 println("write through parameter lost: p.a =", p.a.String())
43 return
44 }
45 if p.b != 14 {
46 println("write through parameter lost: p.b =", p.b.String())
47 return
48 }
49 if seen != 21 {
50 println("named result wrong:", seen.String())
51 return
52 }
53 if bump(4) != 50 {
54 println("assign to parameter lost:", bump(4).String())
55 return
56 }
57 println("param mutable ok")
58 }
59