generic

package
v0.7.4 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Overview

Package generic 提供一组类型安全的泛型/反射小工具。 仅收录标准库 slices/maps 未覆盖的部分。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New[T any]() T

New 创建 T 的可用零值实例:对 map/slice 会 make,对(多级)指针会逐层分配, 因此 New[*Foo]() 返回的是指向零值 Foo 的非 nil 指针,而非 nil。 (需要纯类型时用标准库 reflect.TypeFor[T]() 即可,本包不再重复。)

func Ptr

func Ptr[T any](v T) *T

Ptr 返回 v 的指针,便于给需要 *T 的字段赋字面量。

cfg.Timeout = generic.Ptr(30 * time.Second)

func ToMap

func ToMap[T any, K comparable, V any](s []T, f func(T) (K, V)) map[K]V

ToMap 用 f 把切片转换为 map,常用于按某个字段建索引。

byID := generic.ToMap(users, func(u User) (int, User) { return u.ID, u })

func TypeName

func TypeName(val reflect.Value) string

TypeName 返回 reflect.Value 的人类可读类型名,便于日志/调试:

  • 多级指针自动解引用(**Foo -> "Foo")
  • 函数取其名(method、匿名函数等),匿名函数返回空串

Types

This section is empty.

Jump to

Keyboard shortcuts

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