github.com/powerman/golang-tools@v0.1.11-0.20220410185822-5ad214d8d803/go/ssa/interp/testdata/slice2arrayptr.go (about)

     1  // Copyright 2021 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  // Test for slice to array pointer conversion introduced in go1.17
     6  // See: https://tip.golang.org/ref/spec#Conversions_from_slice_to_array_pointer
     7  
     8  package main
     9  
    10  func main() {
    11  	s := make([]byte, 2, 4)
    12  	if s0 := (*[0]byte)(s); s0 == nil {
    13  		panic("converted from non-nil slice result in nil array pointer")
    14  	}
    15  	if s2 := (*[2]byte)(s); &s2[0] != &s[0] {
    16  		panic("the converted array is not slice underlying array")
    17  	}
    18  	wantPanic(
    19  		func() {
    20  			_ = (*[4]byte)(s) // panics: len([4]byte) > len(s)
    21  		},
    22  		"runtime error: array length is greater than slice length",
    23  	)
    24  
    25  	var t []string
    26  	if t0 := (*[0]string)(t); t0 != nil {
    27  		panic("nil slice converted to *[0]byte should be nil")
    28  	}
    29  	wantPanic(
    30  		func() {
    31  			_ = (*[1]string)(t) // panics: len([1]string) > len(t)
    32  		},
    33  		"runtime error: array length is greater than slice length",
    34  	)
    35  }
    36  
    37  type arr [2]int
    38  
    39  func f() {
    40  	s := []int{1, 2, 3, 4}
    41  	_ = *(*arr)(s)
    42  }
    43  
    44  func wantPanic(fn func(), s string) {
    45  	defer func() {
    46  		err := recover()
    47  		if err == nil {
    48  			panic("expected panic")
    49  		}
    50  		if got := err.(error).Error(); got != s {
    51  			panic("expected panic " + s + " got " + got)
    52  		}
    53  	}()
    54  	fn()
    55  }