modernc.org/gc@v1.0.1-0.20240304020402-f0dba7c97c2b/testdata/errchk/test/fixedbugs/issue16870.go (about)

     1  // run
     2  
     3  // Copyright 2016 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  package main
     8  
     9  import (
    10  	"log"
    11  	"reflect"
    12  )
    13  
    14  func test(got, want interface{}) {
    15  	if !reflect.DeepEqual(got, want) {
    16  		log.Fatalf("got %v, want %v", got, want)
    17  	}
    18  }
    19  
    20  func main() {
    21  	var i int
    22  	var ip *int
    23  	var ok interface{}
    24  
    25  	// Channel receives.
    26  	c := make(chan int, 1)
    27  	c2 := make(chan int)
    28  
    29  	c <- 42
    30  	i, ok = <-c
    31  	test(i, 42)
    32  	test(ok, true)
    33  
    34  	c <- 42
    35  	_, ok = <-c
    36  	test(ok, true)
    37  
    38  	c <- 42
    39  	select {
    40  	case i, ok = <-c:
    41  		test(i, 42)
    42  		test(ok, true)
    43  	}
    44  
    45  	c <- 42
    46  	select {
    47  	case _, ok = <-c:
    48  		test(ok, true)
    49  	}
    50  
    51  	c <- 42
    52  	select {
    53  	case i, ok = <-c:
    54  		test(i, 42)
    55  		test(ok, true)
    56  	default:
    57  		log.Fatal("bad select")
    58  	}
    59  
    60  	c <- 42
    61  	select {
    62  	case _, ok = <-c:
    63  		test(ok, true)
    64  	default:
    65  		log.Fatal("bad select")
    66  	}
    67  
    68  	c <- 42
    69  	select {
    70  	case i, ok = <-c:
    71  		test(i, 42)
    72  		test(ok, true)
    73  	case <-c2:
    74  		log.Fatal("bad select")
    75  	}
    76  
    77  	c <- 42
    78  	select {
    79  	case _, ok = <-c:
    80  		test(ok, true)
    81  	case <-c2:
    82  		log.Fatal("bad select")
    83  	}
    84  
    85  	close(c)
    86  	i, ok = <-c
    87  	test(i, 0)
    88  	test(ok, false)
    89  
    90  	_, ok = <-c
    91  	test(ok, false)
    92  
    93  	// Map indexing.
    94  	m := make(map[int]int)
    95  
    96  	i, ok = m[0]
    97  	test(i, 0)
    98  	test(ok, false)
    99  
   100  	_, ok = m[0]
   101  	test(ok, false)
   102  
   103  	m[0] = 42
   104  	i, ok = m[0]
   105  	test(i, 42)
   106  	test(ok, true)
   107  
   108  	_, ok = m[0]
   109  	test(ok, true)
   110  
   111  	// Type assertions.
   112  	var u interface{}
   113  
   114  	i, ok = u.(int)
   115  	test(i, 0)
   116  	test(ok, false)
   117  
   118  	ip, ok = u.(*int)
   119  	test(ip, (*int)(nil))
   120  	test(ok, false)
   121  
   122  	_, ok = u.(int)
   123  	test(ok, false)
   124  
   125  	u = 42
   126  	i, ok = u.(int)
   127  	test(i, 42)
   128  	test(ok, true)
   129  
   130  	_, ok = u.(int)
   131  	test(ok, true)
   132  
   133  	u = &i
   134  	ip, ok = u.(*int)
   135  	test(ip, &i)
   136  	test(ok, true)
   137  
   138  	_, ok = u.(*int)
   139  	test(ok, true)
   140  }