Source file test/indirect.go

     1  // run
     2  
     3  // Copyright 2009 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 various safe uses of indirection.
     8  
     9  package main
    10  
    11  var m0 map[string]int
    12  var m1 *map[string]int
    13  var m2 *map[string]int = &m0
    14  var m3 map[string]int = map[string]int{"a": 1}
    15  var m4 *map[string]int = &m3
    16  
    17  var s0 string
    18  var s1 *string
    19  var s2 *string = &s0
    20  var s3 string = "a"
    21  var s4 *string = &s3
    22  
    23  var a0 [10]int
    24  var a1 *[10]int
    25  var a2 *[10]int = &a0
    26  
    27  var b0 []int
    28  var b1 *[]int
    29  var b2 *[]int = &b0
    30  var b3 []int = []int{1, 2, 3}
    31  var b4 *[]int = &b3
    32  
    33  func crash() {
    34  	// these uses of nil pointers
    35  	// would crash but should type check
    36  	println("crash",
    37  		len(a1)+cap(a1))
    38  }
    39  
    40  func nocrash() {
    41  	// this is spaced funny so that
    42  	// the compiler will print a different
    43  	// line number for each len call if
    44  	// it decides there are type errors.
    45  	// it might also help in the traceback.
    46  	x :=
    47  		len(m0) +
    48  			len(m3)
    49  	if x != 1 {
    50  		println("wrong maplen")
    51  		panic("fail")
    52  	}
    53  
    54  	x =
    55  		len(s0) +
    56  			len(s3)
    57  	if x != 1 {
    58  		println("wrong stringlen")
    59  		panic("fail")
    60  	}
    61  
    62  	x =
    63  		len(a0) +
    64  			len(a2)
    65  	if x != 20 {
    66  		println("wrong arraylen")
    67  		panic("fail")
    68  	}
    69  
    70  	x =
    71  		len(b0) +
    72  			len(b3)
    73  	if x != 3 {
    74  		println("wrong slicelen")
    75  		panic("fail")
    76  	}
    77  
    78  	x =
    79  		cap(b0) +
    80  			cap(b3)
    81  	if x != 3 {
    82  		println("wrong slicecap")
    83  		panic("fail")
    84  	}
    85  }
    86  
    87  func main() { nocrash() }
    88  

View as plain text