Skip to content

Instantly share code, notes, and snippets.

@wilinz
Last active October 25, 2023 16:16
Show Gist options
  • Save wilinz/2ce7805d43f9b584669b71c0de8e2431 to your computer and use it in GitHub Desktop.
Save wilinz/2ce7805d43f9b584669b71c0de8e2431 to your computer and use it in GitHub Desktop.
go pointer util
package ptr
func ptr[T any](v T) *T {
return &v
}
func unptr[T any](ptr *T) T {
return *ptr
}
@wilinz
Copy link
Author

wilinz commented Oct 25, 2023

Pointer Utility Functions for Golang. The Go's specification says that the operand of the address operation &x must be addressable (ref. https://golang.org/ref/spec#Address_operators ). It means that we can't get the addresses of constants, literals(Integer literals, Floating-point literals, String literals, etc.), and the return values of a function or method. The pointer package makes them addressable, and returns their pointers.

指针实用函数用于处理 Golang 中的指针操作。Go 的规范说明了取地址操作符 & 的操作数必须是可寻址的(参考:https://golang.org/ref/spec#Address_operators)。这意味着我们无法获取常量、字面量(例如整数字面量、浮点数字面量、字符串字面量等)以及函数或方法的返回值的地址。指针包提供了一些函数,可以使它们变得可寻址,并返回它们的指针。

@wilinz
Copy link
Author

wilinz commented Oct 25, 2023

Since Go 1.18

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment