Created
January 12, 2023 20:37
-
-
Save Zhang-Siyang/2ba46ac1c6060fd0e8dd3e880aae3140 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"reflect" | |
"unsafe" | |
) | |
func main() { | |
s := []int{0, 0, 0, 0, 0} | |
fmt.Printf("s:\t\t (len %d cap %d data %#x data %v),\t &s:\t %p\n", len(s), cap(s), | |
reflect.ValueOf(s).Pointer(), *(*[5]int)(unsafe.Pointer(reflect.ValueOf(s).Pointer())), &s) | |
changeLastOne(s) | |
fmt.Printf("s changeLastOne: (len %d cap %d data %#x data %v),\t &s:\t %p\n", len(s), cap(s), | |
reflect.ValueOf(s).Pointer(), *(*[5]int)(unsafe.Pointer(reflect.ValueOf(s).Pointer())), &s) | |
overlay(s) | |
fmt.Printf("s overlay:\t (len %d cap %d data %#x data %v),\t &s:\t %p\n", len(s), cap(s), | |
reflect.ValueOf(s).Pointer(), *(*[5]int)(unsafe.Pointer(reflect.ValueOf(s).Pointer())), &s) | |
replace(s) | |
fmt.Printf("s replace:\t (len %d cap %d data %#x data %v),\t &s:\t %p\n", len(s), cap(s), | |
reflect.ValueOf(s).Pointer(), *(*[5]int)(unsafe.Pointer(reflect.ValueOf(s).Pointer())), &s) | |
} | |
func changeLastOne(slice []int) { | |
slice = slice[:cap(slice)] | |
slice[len(slice)-1] = -1 | |
} | |
func overlay(slice []int) { | |
fmt.Printf("[overlay] slice: (len %d cap %d data %#x data %v),\t &slice: %p\n", len(slice), cap(slice), | |
reflect.ValueOf(slice).Pointer(), *(*[5]int)(unsafe.Pointer(reflect.ValueOf(slice).Pointer())), &slice) | |
slice = []int{1, 2, 3, 4, 5} | |
fmt.Printf("[overlay] slice: (len %d cap %d data %#x data %v),\t &slice: %p\n", len(slice), cap(slice), | |
reflect.ValueOf(slice).Pointer(), *(*[5]int)(unsafe.Pointer(reflect.ValueOf(slice).Pointer())), &slice) | |
} | |
func replace(slice []int) { | |
fmt.Printf("[replace] slice: (len %d cap %d data %#x data %v),\t &slice: %p\n", len(slice), cap(slice), | |
reflect.ValueOf(slice).Pointer(), *(*[5]int)(unsafe.Pointer(reflect.ValueOf(slice).Pointer())), &slice) | |
slice[2] = 1 | |
fmt.Printf("[replace] slice: (len %d cap %d data %#x data %v),\t &slice: %p\n", len(slice), cap(slice), | |
reflect.ValueOf(slice).Pointer(), *(*[5]int)(unsafe.Pointer(reflect.ValueOf(slice).Pointer())), &slice) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment