reflect

package
v2.16.0 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2024 License: MIT Imports: 1 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Cast

func Cast[X any, Y any](x X) Y

Cast converts between values and interfaces.

Example
package main

import (
	"fmt"
	"io"

	"github.com/tawesoft/golib/v2/fun/slices"
	"github.com/tawesoft/golib/v2/must"
	"github.com/tawesoft/golib/v2/operator/reflect"
)

type Handle struct {
	closed bool
}

func (h *Handle) Close() error {
	if h.closed {
		return fmt.Errorf("handle already closed")
	}
	h.closed = true
	return nil
}

func OpenHandle() *Handle {
	return &Handle{}
}

func main() {
	handles := []*Handle{
		OpenHandle(),
		OpenHandle(),
		OpenHandle(),
	}

	closeEverything := func(closers ...io.Closer) {
		for _, closer := range closers {
			must.Check(closer.Close())
		}
	}

	closeables := slices.Map(reflect.Cast[*Handle, io.Closer], handles)
	closeEverything(closeables...)

	checkClosed := func(handles ...*Handle) {
		for _, handle := range handles {
			must.True(handle.closed)
		}
	}

	handlesAgain := slices.Map(reflect.Cast[io.Closer, *Handle], closeables)
	checkClosed(handlesAgain...)

}
Output:

Types

This section is empty.

Jump to

Keyboard shortcuts

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