Source file test/convert4.go

     1  // run
     2  
     3  // Copyright 2020 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 conversion from slice to array pointer.
     8  
     9  package main
    10  
    11  func wantPanic(fn func(), s string) {
    12  	defer func() {
    13  		err := recover()
    14  		if err == nil {
    15  			panic("expected panic")
    16  		}
    17  		if got := err.(error).Error(); got != s {
    18  			panic("expected panic " + s + " got " + got)
    19  		}
    20  	}()
    21  	fn()
    22  }
    23  
    24  func main() {
    25  	s := make([]byte, 8, 10)
    26  	if p := (*[8]byte)(s); &p[0] != &s[0] {
    27  		panic("*[8]byte conversion failed")
    28  	}
    29  	wantPanic(
    30  		func() {
    31  			_ = (*[9]byte)(s)
    32  		},
    33  		"runtime error: cannot convert slice with length 8 to pointer to array with length 9",
    34  	)
    35  
    36  	var n []byte
    37  	if p := (*[0]byte)(n); p != nil {
    38  		panic("nil slice converted to *[0]byte should be nil")
    39  	}
    40  
    41  	z := make([]byte, 0)
    42  	if p := (*[0]byte)(z); p == nil {
    43  		panic("empty slice converted to *[0]byte should be non-nil")
    44  	}
    45  
    46  	// Test with named types
    47  	type Slice []int
    48  	type Int4 [4]int
    49  	type PInt4 *[4]int
    50  	ii := make(Slice, 4)
    51  	if p := (*Int4)(ii); &p[0] != &ii[0] {
    52  		panic("*Int4 conversion failed")
    53  	}
    54  	if p := PInt4(ii); &p[0] != &ii[0] {
    55  		panic("PInt4 conversion failed")
    56  	}
    57  }
    58  
    59  // test static variable conversion
    60  
    61  var (
    62  	ss  = make([]string, 10)
    63  	s5  = (*[5]string)(ss)
    64  	s10 = (*[10]string)(ss)
    65  
    66  	ns  []string
    67  	ns0 = (*[0]string)(ns)
    68  
    69  	zs  = make([]string, 0)
    70  	zs0 = (*[0]string)(zs)
    71  )
    72  
    73  func init() {
    74  	if &ss[0] != &s5[0] {
    75  		panic("s5 conversion failed")
    76  	}
    77  	if &ss[0] != &s10[0] {
    78  		panic("s5 conversion failed")
    79  	}
    80  	if ns0 != nil {
    81  		panic("ns0 should be nil")
    82  	}
    83  	if zs0 == nil {
    84  		panic("zs0 should not be nil")
    85  	}
    86  }
    87  

View as plain text