Skip to content

Commit

Permalink
work on chapter 14 (test)
Browse files Browse the repository at this point in the history
  • Loading branch information
MKaczkow committed Mar 28, 2024
1 parent 96b054f commit cfb6cbb
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion learning_go/14_reflection_unsafe_cgo/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
> [!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

0 comments on commit cfb6cbb

Please sign in to comment.