1 | // Copyright 2020 The Go Authors. All rights reserved. |
---|---|
2 | // Use of this source code is governed by a BSD-style |
3 | // license that can be found in the LICENSE file. |
4 | |
5 | // This file contains tests for the useless-assignment checker. |
6 | |
7 | package testdata |
8 | |
9 | import "math/rand" |
10 | |
11 | type ST struct { |
12 | x int |
13 | l []int |
14 | } |
15 | |
16 | func (s *ST) SetX(x int, ch chan int) { |
17 | // Accidental self-assignment; it should be "s.x = x" |
18 | x = x // want "self-assignment of x to x" |
19 | // Another mistake |
20 | s.x = s.x // want "self-assignment of s.x to s.x" |
21 | |
22 | s.l[0] = s.l[0] // want "self-assignment of s.l.0. to s.l.0." |
23 | |
24 | // Bail on any potential side effects to avoid false positives |
25 | s.l[num()] = s.l[num()] |
26 | rng := rand.New(rand.NewSource(0)) |
27 | s.l[rng.Intn(len(s.l))] = s.l[rng.Intn(len(s.l))] |
28 | s.l[<-ch] = s.l[<-ch] |
29 | } |
30 | |
31 | func num() int { return 2 } |
32 | |
33 | func Index() { |
34 | s := []int{1} |
35 | s[0] = s[0] // want "self-assignment" |
36 | |
37 | var a [5]int |
38 | a[0] = a[0] // want "self-assignment" |
39 | |
40 | pa := &[2]int{1, 2} |
41 | pa[1] = pa[1] // want "self-assignment" |
42 | |
43 | var pss *struct { // report self assignment despite nil dereference |
44 | s []int |
45 | } |
46 | pss.s[0] = pss.s[0] // want "self-assignment" |
47 | |
48 | m := map[int]string{1: "a"} |
49 | m[0] = m[0] // bail on map self-assignments due to side effects |
50 | m[1] = m[1] // not modeling what elements must be in the map |
51 | (m[2]) = (m[2]) // even with parens |
52 | type Map map[string]bool |
53 | named := make(Map) |
54 | named["s"] = named["s"] // even on named maps. |
55 | var psm *struct { |
56 | m map[string]int |
57 | } |
58 | psm.m["key"] = psm.m["key"] // handles dereferences |
59 | } |
60 |
Members