From cfb6cbb96a94ea64c21192086a6162a65e1659a1 Mon Sep 17 00:00:00 2001 From: Maciej Kaczkowski Date: Thu, 28 Mar 2024 15:37:33 +0100 Subject: [PATCH] work on chapter 14 (test) --- .../14_reflection_unsafe_cgo/README.md | 33 ++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/learning_go/14_reflection_unsafe_cgo/README.md b/learning_go/14_reflection_unsafe_cgo/README.md index e113c28..1a03d16 100644 --- a/learning_go/14_reflection_unsafe_cgo/README.md +++ b/learning_go/14_reflection_unsafe_cgo/README.md @@ -15,7 +15,38 @@ - when you define `Foo` struct, it has: - `Kind` -> `reflect.Struct` - `Type` -> `packetname.Foo` +* `reflect.New` is reflective version of `new` operator +* there are also equivalents of `make` +* it's possible to create custom marshalling and unmarshalling functions using `reflect` package and reflection mechanism ### Unsafe +* truly unsafe +* weird +* 1 type -> `Pointer` +* 3 functions + - `Sizeof` -> returns size of the variable + - `Offsetof` -> returns offset of the field in the struct + - `Alignof` -> returns alignment of the field in the struct +* based on [this empirical study from arxiv](https://arxiv.org/pdf/2006.09973.pdf) some colorful stuff -### Cgo \ No newline at end of file +> [!TIP] +> Correct way to convert `float64` to `uint64` using `unsafe` package (conversion must appear in the same line s operations, otherwise the pointer could be collected by garbage collector before dereferencing) +> ```go +> import unsafe +> +> func Float64(f float64) uint64 { +> return *(*uint64)(unsafe.Pointer(&f)) +> } +> ``` + +> [!CAUTION] +> Incorrect way, contrary to explained above +> ```go +> import unsafe +> +> u := uintptr(p) +> p = unsafe.Pointer(u + offset) +> ``` + + +### Cgo