Skip to content

rocketlaunchr/unsafe

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 

Repository files navigation

⭐   the project to show your appreciation. ↗️

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 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 {
	e 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("e"))
*(*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("e"), "New Value 2")

Example 2 - Reading a field

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

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

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages