unsafe

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2025 License: MIT Imports: 3 Imported by: 0

README

⭐   the project to show your appreciation. :arrow_upper_right:

Unsafe

This package is for "safely" modifying unexported fields of a struct.

Safety Considerations

Contrary to popular belief, the unsafe package is actually safe to use - provided you know what you are doing.

  1. You need to ensure the newValue is the same type as the field's type.
  2. You need to make sure the field is not being modifed by multiple go-routines concurrently.
  3. Read Safety and Numbers — Understanding unsafe in Go
  4. Read Exploring ‘unsafe’ Features in Go 1.20: A Hands-On Demo and Modifying Private Variables of a Struct in Go Using unsafe and reflect.

Example 1 - Setting a field

type Example struct {
	private string // unexported string 
}

Let's modify the Example struct's e field.

import "github.com/rocketlaunchr/unsafe"

e := Example{}

// Option 1
ptr := unsafe.SetField[string](&e, unsafe.F("private"))
*(*string)(ptr) = "New Value" // Note: If the field type is string, then ptr must be cast to *string

// Option 2
unsafe.SetField(&e, unsafe.F("private"), "New Value 2")

Example 2 - Reading a field

val := unsafe.Value[string](&e, unsafe.F("private"))

Other useful packages

  • awesome-svelte - Resources for killing react
  • dataframe-go - Statistics and data manipulation
  • dbq - Zero boilerplate database operations for Go
  • electron-alert - SweetAlert2 for Electron Applications
  • go-pool - A Generic pool
  • igo - A Go transpiler with cool new syntax such as fordefer (defer for for-loops)
  • mysql-go - Properly cancel slow MySQL queries
  • react - Build front end applications using Go
  • remember-go - Cache slow database queries
  • testing-go - Testing framework for unit testing

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Alignof

func Alignof[ArbitraryType _ArbitraryType](x ArbitraryType) uintptr

Alignof

See: https://pkg.go.dev/unsafe#Alignof

func ClearOut added in v1.4.0

func ClearOut(baseAddr unsafe.Pointer, clearout [][2]uintptr)

ClearOut zeros out selected blocks of memory. clearout is a slice containing offset-size pairs. The offset is always relative to baseAddr.

NOTE: It uses runtime.memclrNoHeapPointers so make sure you read documentation on when it is safe to use.

func F

func F[F interface{ int | []int | string | uintptr }](f F, typ ...Type) field

F is shorthand for the Field function.

func Field

func Field[F interface{ int | []int | string | uintptr }](f F, typ ...Type) field

Field selects a field in a struct. The field can be selected by passing an integer or a (name) string. An optional type constraint can be provided as a safety precaution to ensure that the field's type is what you expected.

func FindPointerFields added in v1.2.0

func FindPointerFields(t reflect.Type) [][2]uintptr

FindPointerFields finds in a struct the offsets (and corresponding sizes) of all fields that contain pointers and other reference types.

func Malloc added in v1.2.0

func Malloc(size uintptr, zerofill bool, typ ...reflect.Type) unsafe.Pointer

Malloc allocates contiguous blocks of memory without zeroing. However, the memory will be cleared when zerofill is set.

All allocated memory must sensibly be filled by the developer immediately, since the pre-existing data may contain garbage.

WARNING: If the returned pointer will be cast to a struct with fields containing pointers, then typ must be provided to inform the garbage collector. As an optimization, typ can be stored in a global variable and reused.

NOTE: Reference types (eg. strings, slices, interfaces, channels, maps etc.) contain pointers.

Example:

type Person struct {
   name  [50]byte
   age   int
   phone int
}

ptr := Malloc(unsafe.Sizeof(Person{}), false)
ClearOut(ptr, [][2]uintptr{})
p := *(*Person)(ptr)

func New added in v1.2.0

func New[T any, PtrT interface {
	*T
	UnsafeClearOutFields
}](typ ...reflect.Type,
) *T

New allocates memory for a struct without zeroing. A pointer to the newly allocated value is returned. The returned struct is not guaranteed to be the zero value.

NOTE: UnsafeClearOutFields must be implemented as a method with a pointer receiver. UnsafeClearOutFields is used to selectively zero fields.

WARNING: T must not have fields containing pointers. ...But if it does contain pointers, provide typ=nil to inform the garbage collector. As an optimization, typ can be stored in a global variable and reused.

NOTE: Reference types (eg. strings, slices, interfaces, channels, maps etc.) contain pointers.

Example:

type Person struct {
   name  [50]byte
   age   int
   phone int
}

func (p *Person) UnsafeClearOutFields() [][2]uintptr {
	return [][2]uintptr {
		{unsafe.Offsetof(Person{}.name), unsafe.Sizeof(Person{}.name)},
		{unsafe.Offsetof(Person{}.phone), unsafe.Sizeof(Person{}.phone)},
	}
	return nil
}

func main() {
   p := New[Person]() // like p := new(Person)
}

func NewZero deprecated added in v1.2.2

func NewZero[T any](typ ...reflect.Type) *T

NewZero allocates memory for a zero-value struct. A pointer to the newly allocated value is returned. It is equivalent to new(T) (but seems to be faster).

WARNING: T must not have fields containing pointers. ...But if it does contain pointers, provide typ=nil to inform the garbage collector. As an optimization, typ can be stored in a global variable and reused.

NOTE: Reference types (eg. strings, slices, interfaces, channels, maps etc.) contain pointers.

Example:

p := NewZero[T]()

Deprecated: From Go1.26+, new(T) will be on par or faster than NewZero.

func Sizeof

func Sizeof[ArbitraryType _ArbitraryType](x ArbitraryType) uintptr

Sizeof

See: https://pkg.go.dev/unsafe#Sizeof

func Slice

func Slice[ArbitraryType _ArbitraryType, IntegerType _IntegerType](ptr *ArbitraryType, len IntegerType) []ArbitraryType

Slice

See: https://pkg.go.dev/unsafe#Slice

func SliceData

func SliceData[ArbitraryType _ArbitraryType](slice []ArbitraryType) *ArbitraryType

SliceData

See: https://pkg.go.dev/unsafe#SliceData

func String

func String[IntegerType _IntegerType](ptr *byte, len IntegerType) string

String

See: https://pkg.go.dev/unsafe#String

func StringData

func StringData(str string) *byte

StringData

See: https://pkg.go.dev/unsafe#StringData

func Value added in v1.0.1

func Value[T any](strct any, f field) T

Value returns the value of the unexported field of a struct.

NOTE: This function panics if strct is not actually a struct or the field could not be found.

Types

type Pointer

type Pointer = unsafe.Pointer

Pointer

See: https://pkg.go.dev/unsafe#Pointer

func Add

func Add[IntegerType _IntegerType](ptr Pointer, len IntegerType) Pointer

Add

See: https://pkg.go.dev/unsafe#Add

func SetField

func SetField[T any](strct any, f field, newValue ...T) Pointer

SetField allows unexported fields of a struct to be modified. It returns a Pointer to the field if you wish to change the value externally instead of by passing a new value.

NOTE: This function panics if strct is not actually a struct or the field could not be found.

type Type added in v1.1.2

type Type = reflect.Type

Type

See: https://pkg.go.dev/reflect#Type

func TypeFor added in v1.1.2

func TypeFor[T any]() Type

TypeFor returns the Type that represents the type argument T.

func TypeOf added in v1.1.2

func TypeOf(i any) Type

TypeOf returns the reflection Type that represents the dynamic type of i. If i is a nil interface value, TypeOf returns nil.

type UnsafeClearOutFields added in v1.4.0

type UnsafeClearOutFields interface {
	// UnsafeClearOutFields must be implemented on the pointer type *T.
	// The return values can be hardcoded using unsafe.Offsetof() and unsafe.Sizeof().
	UnsafeClearOutFields() [][2]uintptr
}

UnsafeClearOutFields is used to return the offset and size of each field of a struct that should be cleared.

Jump to

Keyboard shortcuts

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