【Duke】不安全编程 038 - PingPongGooo/GoFoundation GitHub Wiki
unsafe 使用场景, 外部c程序 ,交互时用到 unsafe
“不安全”行为的危险性
i := 10
f := *(*float64)(unsafe.Pointer(&i))
func TestUnsafe(t *testing.T) {
i := 10
f := *(*float64)(unsafe.Pointer(&i))
t.Log(unsafe.Pointer(&i))
t.Log(f)
}
=== RUN TestUnsafe
--- PASS: TestUnsafe (0.00s)
flexible_reflect_test.go:88: 0xc00000a358
flexible_reflect_test.go:89: 5e-323
PASS
type MyInt int
// 合理的类型转换
func TestConvert(t *testing.T){
a := []int{1,2,3,4}
b := *(*[]MyInt)(unsafe.Pointer(&a))
t.Log(b)
}
=== RUN TestConvert
--- PASS: TestConvert (0.00s)
flexible_reflect_test.go:98: [1 2 3 4]
PASS