unsafe
package
#Reading
#Examples
// - bytes_and_strings.go -
package main
import (
"unsafe"
"github.com/davecgh/go-spew/spew"
)
func main() {
s, b := "string", []byte("string")
spew.Dump(*(*[]byte)(unsafe.Pointer(&s)))
spew.Dump(*(*string)(unsafe.Pointer(&b)))
}
// - main.go -
package main
import (
"fmt"
"unsafe"
)
type Programmer struct {
name string
language string
}
func main() {
p := Programmer{"stefno", "go"}
fmt.Println(p)
name := (*string)(unsafe.Pointer(&p))
*name = "qcrao"
lang := (*string)(unsafe.Pointer(uintptr(unsafe.Pointer(&p)) + unsafe.Offsetof(p.language)))
*lang = "Golang"
fmt.Println(p)
}
// - slice.go -
package main
import (
"reflect"
"unsafe"
"github.com/davecgh/go-spew/spew"
)
func main() {
/// slices...
data := []int{1, 2, 3, 4, 5}
var out []byte
in := (*reflect.SliceHeader)(unsafe.Pointer(&data))
outHeader := (*reflect.SliceHeader)(unsafe.Pointer(&out))
outHeader.Data = in.Data
outHeader.Len = in.Len * int(unsafe.Sizeof(&data[0]))
outHeader.Cap = in.Cap * int(unsafe.Sizeof(&data[0]))
// out is altered!
spew.Dump(out)
}
// - struct.go -
package main
import (
"unsafe"
"github.com/davecgh/go-spew/spew"
)
// packing struct to butes
func main() {
// structs...
type Struct struct {
Src int32
Dst int32
SrcPort uint16
DstPort uint16
}
var struct_value Struct = Struct{1, 2, 3, 4}
const size = int(unsafe.Sizeof(Struct{}))
var asByteSlice []byte = (*(*[size]byte)(unsafe.Pointer(&struct_value)))[:]
spew.Dump(asByteSlice)
}