unsafe

package
v1.2.132 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2025 License: MIT Imports: 1 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bytes

func Bytes[T any](v T) []byte

Bytes returns a byte slice whose underlying array starts at ptr of v and whose length and capacity are len(v). Bytes(v) is equivalent to

(*[unsafe.Sizeof(v)]byte)(unsafe.Pointer(&v))[:]

except that, as a special case, if ptr is nil and len is zero, Slice returns nil.

Example
package main

import (
	"fmt"

	"github.com/searKing/golang/go/exp/unsafe"
)

func main() {
	fmt.Printf("%v\n", unsafe.Bytes(int8(1)))
	fmt.Printf("%v\n", unsafe.Bytes(int16(1)))
	fmt.Printf("%v\n", unsafe.Bytes(int32(1)))
	fmt.Printf("%v\n", unsafe.Bytes([0]byte{}))
	fmt.Printf("%v\n", unsafe.Bytes([2]byte{}))
	fmt.Printf("%v\n", unsafe.Bytes([2]byte{1, 2}))
	fmt.Printf("%v\n", unsafe.Bytes(struct {
		Age  int8
		Name [2]byte
	}{Age: 1, Name: [2]byte{2, 3}}))

}
Output:

[1]
[1 0]
[1 0 0 0]
[]
[0 0]
[1 2]
[1 2 3]

func Placement

func Placement[T any](s []byte) *T

Placement returns a T pointer whose underlying bytes construct objects in allocated storage.

Construct a “T” object, placing it directly into your pre-allocated storage at memory address “s”.

except that, as a special case, if s is nil or len is zero, Placement returns nil.

Example
package main

import (
	"fmt"

	"github.com/searKing/golang/go/exp/unsafe"
)

func main() {
	fmt.Printf("%+v\n", *unsafe.Placement[int8]([]byte{1}))
	fmt.Printf("%+v\n", *unsafe.Placement[int16]([]byte{1, 0}))
	fmt.Printf("%+v\n", *unsafe.Placement[int32]([]byte{1, 0, 0, 0}))
	fmt.Printf("%+v\n", unsafe.Placement[[0]byte](nil))
	fmt.Printf("%+v\n", unsafe.Placement[[0]byte]([]byte{}))
	fmt.Printf("%+v\n", unsafe.Placement[[2]byte](nil))
	fmt.Printf("%+v\n", unsafe.Placement[[2]byte]([]byte{}))
	fmt.Printf("%+v\n", *unsafe.Placement[[2]byte]([]byte{1, 2}))
	fmt.Printf("%+v\n", *unsafe.Placement[struct {
		Age  int8
		Name [2]byte
	}]([]byte{1, 2, 3}))

}
Output:

1
1
1
<nil>
<nil>
<nil>
<nil>
[1 2]
{Age:1 Name:[2 3]}

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL