| 1 | package a |
|---|---|
| 2 | |
| 3 | type T1 struct{ x int } |
| 4 | |
| 5 | type T2 struct { |
| 6 | x int |
| 7 | y int |
| 8 | } |
| 9 | |
| 10 | type T3 struct{ y *T1 } |
| 11 | |
| 12 | func BadWrites() { |
| 13 | // Test struct field writes. |
| 14 | var s1 T1 |
| 15 | s1.x = 10 // want "unused write to field x" |
| 16 | |
| 17 | // Test array writes. |
| 18 | var s2 [10]int |
| 19 | s2[1] = 10 // want "unused write to array index 1:int" |
| 20 | |
| 21 | // Test range variables of struct type. |
| 22 | s3 := []T1{T1{x: 100}} |
| 23 | for i, v := range s3 { |
| 24 | v.x = i // want "unused write to field x" |
| 25 | } |
| 26 | |
| 27 | // Test the case where a different field is read after the write. |
| 28 | s4 := []T2{T2{x: 1, y: 2}} |
| 29 | for i, v := range s4 { |
| 30 | v.x = i // want "unused write to field x" |
| 31 | _ = v.y |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | func (t T1) BadValueReceiverWrite(v T2) { |
| 36 | t.x = 10 // want "unused write to field x" |
| 37 | v.y = 20 // want "unused write to field y" |
| 38 | } |
| 39 | |
| 40 | func GoodWrites(m map[int]int) { |
| 41 | // A map is copied by reference such that a write will affect the original map. |
| 42 | m[1] = 10 |
| 43 | |
| 44 | // Test struct field writes. |
| 45 | var s1 T1 |
| 46 | s1.x = 10 |
| 47 | print(s1.x) |
| 48 | |
| 49 | // Test array writes. |
| 50 | var s2 [10]int |
| 51 | s2[1] = 10 |
| 52 | // Current the checker doesn't distinguish index 1 and index 2. |
| 53 | _ = s2[2] |
| 54 | |
| 55 | // Test range variables of struct type. |
| 56 | s3 := []T1{T1{x: 100}} |
| 57 | for i, v := range s3 { // v is a copy |
| 58 | v.x = i |
| 59 | _ = v.x // still a usage |
| 60 | } |
| 61 | |
| 62 | // Test an object with multiple fields. |
| 63 | o := &T2{x: 10, y: 20} |
| 64 | print(o) |
| 65 | |
| 66 | // Test an object of embedded struct/pointer type. |
| 67 | t1 := &T1{x: 10} |
| 68 | t2 := &T3{y: t1} |
| 69 | print(t2) |
| 70 | } |
| 71 | |
| 72 | func (t *T1) GoodPointerReceiverWrite(v *T2) { |
| 73 | t.x = 10 |
| 74 | v.y = 20 |
| 75 | } |
| 76 |
Members