github.com/cockroachdb/tools@v0.0.0-20230222021103-a6d27438930d/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 f() 37 } 38 39 type arr [2]int 40 41 func f() { 42 s := []int{1, 2, 3, 4} 43 _ = *(*arr)(s) 44 } 45 46 func wantPanic(fn func(), s string) { 47 defer func() { 48 err := recover() 49 if err == nil { 50 panic("expected panic") 51 } 52 if got := err.(error).Error(); got != s { 53 panic("expected panic " + s + " got " + got) 54 } 55 }() 56 fn() 57 }