Documentation
¶
Overview ¶
Package instance provides utilities for creating instances of generic types.
This package helps with dynamic type instantiation, particularly useful when working with generics where you need to create new instances at runtime.
Creating Instances ¶
Use New to create an instance of any type:
// For pointer types (like proto messages) user := instance.New[*pb.User]() // Returns allocated *pb.User // For value types count := instance.New[int]() // Returns 0 name := instance.New[string]() // Returns ""
Use Cases ¶
Proto message instantiation:
func unmarshalProto[P proto.Message](data []byte) (P, error) {
p := instance.New[P]() // P is typically *pb.SomeMessage
err := proto.Unmarshal(data, p)
return p, err
}
Generic container initialization:
func createContainer[T any]() *Container[T] {
return &Container[T]{
value: instance.New[T](),
}
}
gRPC response handling:
reply := instance.New[ResponseType]() err := client.Call(ctx, req, reply)
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func New ¶
func New[T any]() T
New returns a new instance of type T.
For pointer types, it allocates memory and returns a pointer to a new instance. For value types, it returns the zero value.
This is particularly useful when working with generics where the concrete type is not known at compile time, such as proto messages or generic containers.
Example:
// Pointer type (common for proto messages)
user := instance.New[*pb.User]() // Returns &pb.User{}
// Value type
count := instance.New[int]() // Returns 0
name := instance.New[string]() // Returns ""
func Zero ¶
func Zero[T any]() T
Zero returns the zero value for type T.
This is helpful when you need to explicitly return a zero value in generic code, though in most cases you can just use `var zero T`.
Example:
func getOrZero[T any](m map[string]T, key string) T {
if val, ok := m[key]; ok {
return val
}
return instance.Zero[T]()
}
Types ¶
This section is empty.