github.com/cockroachdb/tools@v0.0.0-20230222021103-a6d27438930d/go/ssa/interp/testdata/slice2array.go (about)

     1  // Copyright 2022 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 conversion introduced in go1.20
     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, 3, 4)
    12  	s[0], s[1], s[2] = 2, 3, 5
    13  	a := ([2]byte)(s)
    14  	s[0] = 7
    15  
    16  	if a != [2]byte{2, 3} {
    17  		panic("converted from non-nil slice to array")
    18  	}
    19  
    20  	{
    21  		var s []int
    22  		a := ([0]int)(s)
    23  		if a != [0]int{} {
    24  			panic("zero len array is not equal")
    25  		}
    26  	}
    27  
    28  	if emptyToEmptyDoesNotPanic() {
    29  		panic("no panic expected from emptyToEmptyDoesNotPanic()")
    30  	}
    31  	if !threeToFourDoesPanic() {
    32  		panic("panic expected from threeToFourDoesPanic()")
    33  	}
    34  
    35  	if !fourPanicsWhileOneDoesNot[[4]int]() {
    36  		panic("panic expected from fourPanicsWhileOneDoesNot[[4]int]()")
    37  	}
    38  	if fourPanicsWhileOneDoesNot[[1]int]() {
    39  		panic("no panic expected from fourPanicsWhileOneDoesNot[[1]int]()")
    40  	}
    41  
    42  	if !fourPanicsWhileZeroDoesNot[[4]int]() {
    43  		panic("panic expected from fourPanicsWhileZeroDoesNot[[4]int]()")
    44  	}
    45  	if fourPanicsWhileZeroDoesNot[[0]int]() {
    46  		panic("no panic expected from fourPanicsWhileZeroDoesNot[[0]int]()")
    47  	}
    48  }
    49  
    50  func emptyToEmptyDoesNotPanic() (raised bool) {
    51  	defer func() {
    52  		if e := recover(); e != nil {
    53  			raised = true
    54  		}
    55  	}()
    56  	var s []int
    57  	_ = ([0]int)(s)
    58  	return false
    59  }
    60  
    61  func threeToFourDoesPanic() (raised bool) {
    62  	defer func() {
    63  		if e := recover(); e != nil {
    64  			raised = true
    65  		}
    66  	}()
    67  	s := make([]int, 3, 5)
    68  	_ = ([4]int)(s)
    69  	return false
    70  }
    71  
    72  func fourPanicsWhileOneDoesNot[T [1]int | [4]int]() (raised bool) {
    73  	defer func() {
    74  		if e := recover(); e != nil {
    75  			raised = true
    76  		}
    77  	}()
    78  	s := make([]int, 3, 5)
    79  	_ = T(s)
    80  	return false
    81  }
    82  
    83  func fourPanicsWhileZeroDoesNot[T [0]int | [4]int]() (raised bool) {
    84  	defer func() {
    85  		if e := recover(); e != nil {
    86  			raised = true
    87  		}
    88  	}()
    89  	var s []int
    90  	_ = T(s)
    91  	return false
    92  }