Documentation
¶
Overview ¶
Package kit provides various reflect type functions for GoKi system, including:
* kit.TypeRegistry (types.go) for associating string names with reflect.Type values, to allow dynamic marshaling of structs, and also bidirectional string conversion of const int iota (enum) types. It is used by the GoKi ki system, hence the kit (ki types) name.
To register a new type, add:
var KiT_TypeName = kit.Types.AddType(&TypeName{}, [props|nil])
where the props is a map[string]interface{} of optional properties that can be associated with the type -- this is used in the GoGi graphical interface system for example to color objects of different types using the background-color property. KiT_TypeName variable can be conveniently used wherever a reflect.Type of that type is needed.
* kit.EnumRegistry (enums.go) that registers constant int iota (aka enum) types, and provides general conversion utilities to / from string, int64, general properties associated with enum types, and deals with bit flags
* kit.Type (type.go) struct provides JSON and XML Marshal / Unmarshal functions for saving / loading reflect.Type using registrered type names.
* convert.go: robust interface{}-based type conversion routines that are useful in more lax user-interface contexts where "common sense" conversions between strings, numbers etc are useful
* embeds.go: various functions for managing embedded struct types, e.g., determining if a given type embeds another type (directly or indirectly), and iterating over fields to flatten the otherwise nested nature of the field encoding in embedded types.
Index ¶
- Constants
- Variables
- func AllErrors(errs []error, maxN int) error
- func AllFields(typ reflect.Type) []reflect.StructField
- func AllFieldsN(typ reflect.Type) int
- func AllFieldsTypeFunc(typ reflect.Type, fun func(typ reflect.Type, field reflect.StructField) bool) bool
- func BitFlagsFromString(bflg *int64, str string, en any) error
- func BitFlagsToString(bflg int64, en any) string
- func BitFlagsTypeFromString(bflg *int64, str string, et reflect.Type, n int) error
- func CloneToType(typ reflect.Type, val any) reflect.Value
- func CopyMapRobust(to, fm any) error
- func CopySliceRobust(to, fm any) error
- func Embed(stru any, embed reflect.Type) any
- func EmbedImplements(typ, iface reflect.Type) bool
- func EnumBitDepthCheck(typ reflect.Type, n int64) error
- func EnumIfaceFromInt64(ival int64, typ reflect.Type) any
- func EnumIfaceFromString(str string, typ reflect.Type) any
- func EnumIfaceToInt64(eval any) int64
- func EnumIfaceToString(eval any) string
- func EnumInt64ToString(ival int64, typ reflect.Type) string
- func EnumMarshalJSON(eval any) ([]byte, error)
- func EnumMarshalText(eval any) ([]byte, error)
- func EnumUnmarshalJSON(eval any, b []byte) error
- func EnumUnmarshalText(eval any, b []byte) error
- func FieldByPath(typ reflect.Type, path string) (reflect.StructField, bool)
- func FieldValueByPath(stru any, path string) (reflect.Value, bool)
- func FlatFieldByName(typ reflect.Type, nm string) (reflect.StructField, bool)
- func FlatFieldInterfaceByName(stru any, nm string) any
- func FlatFieldInterfaces(stru any) []any
- func FlatFieldTag(typ reflect.Type, nm, tag string) string
- func FlatFieldVals(stru any) []reflect.Value
- func FlatFieldValueByName(stru any, nm string) reflect.Value
- func FlatFields(typ reflect.Type) []reflect.StructField
- func FlatFieldsTypeFunc(typ reflect.Type, fun func(typ reflect.Type, field reflect.StructField) bool) bool
- func FlatFieldsValueFunc(stru any, ...) bool
- func HasUpperCase(str string) bool
- func IfaceIsNil(it any) bool
- func KindIsBasic(vk reflect.Kind) bool
- func LongTypeName(typ reflect.Type) string
- func MakeMap(typ reflect.Type) reflect.Value
- func MakeOfType(typ reflect.Type) reflect.Value
- func MakePtrValue(v reflect.Value) reflect.Value
- func MakeSlice(typ reflect.Type, len, cap int) reflect.Value
- func MapAdd(mv any)
- func MapDelete(mv any, key any)
- func MapDeleteAll(mv any)
- func MapDeleteValue(mv any, key reflect.Value)
- func MapElsN(mp any) int
- func MapElsValueFun(mp any, fun func(mp any, typ reflect.Type, key, val reflect.Value) bool) bool
- func MapKeyType(mp any) reflect.Type
- func MapSort(mp any, byKey, ascending bool) []reflect.Value
- func MapStructElsN(mp any) int
- func MapStructElsValueFun(mp any, fun func(mp any, typ reflect.Type, val reflect.Value) bool) bool
- func MapValueSort(mpvnp reflect.Value, keys []reflect.Value, ascending bool) error
- func MapValueType(mp any) reflect.Type
- func Max32(a, b float32) float32
- func Min32(a, b float32) float32
- func MinPos(a, b float64) float64
- func MinPos32(a, b float32) float32
- func NonPtrInterface(el any) any
- func NonPtrType(typ reflect.Type) reflect.Type
- func NonPtrValue(v reflect.Value) reflect.Value
- func OnePtrInterface(el any) any
- func OnePtrType(typ reflect.Type) reflect.Type
- func OnePtrUnderlyingValue(v reflect.Value) reflect.Value
- func OnePtrValue(v reflect.Value) reflect.Value
- func PtrInterface(el any) any
- func PtrType(typ reflect.Type) reflect.Type
- func PtrValue(v reflect.Value) reflect.Value
- func Sel(a ...any) []any
- func SetEnumIfaceFromInt64(eval any, ival int64, typ reflect.Type) error
- func SetEnumIfaceFromString(eptr any, str string) error
- func SetEnumValueFromInt64(eval reflect.Value, ival int64) error
- func SetEnumValueFromString(eval reflect.Value, str string) error
- func SetFromDefaultTags(obj any) error
- func SetMapRobust(mp, ky, val reflect.Value) bool
- func SetRobust(to, frm any) bool
- func SetTypeProp(props map[string]any, key string, val any)
- func ShortTypeName(typ reflect.Type) string
- func SliceDeleteAt(sl any, idx int)
- func SliceElType(sl any) reflect.Type
- func SliceNewAt(sl any, idx int)
- func SliceSort(sl any, ascending bool) error
- func String(k Type) string
- func StringJSON(it any) string
- func StructSliceSort(struSlice any, fldIdx []int, ascending bool) error
- func StructTags(tags reflect.StructTag) map[string]string
- func ToBool(it any) (bool, bool)
- func ToFloat(it any) (float64, bool)
- func ToFloat32(it any) (float32, bool)
- func ToInt(it any) (int64, bool)
- func ToString(it any) string
- func ToStringPrec(it any, prec int) string
- func TypeEmbeds(typ, embed reflect.Type) bool
- func TypeFor[T any]() reflect.Type
- func TypeProp(props map[string]any, key string) (any, bool)
- func UnhideIfaceValue(v reflect.Value) reflect.Value
- func ValueIsZero(v reflect.Value) bool
- func ValueSliceSort(sl []reflect.Value, ascending bool) error
- type Describer
- type EnumRegistry
- func (tr *EnumRegistry) AddEnum(en any, bitFlag bool, props map[string]any) reflect.Type
- func (tr *EnumRegistry) AddEnumAltLower(en any, bitFlag bool, props map[string]any, prefix string) reflect.Type
- func (tr *EnumRegistry) AddEnumExt(parTyp reflect.Type, en any, bitFlag bool, props map[string]any) reflect.Type
- func (tr *EnumRegistry) AddEnumExtAltLower(parTyp reflect.Type, en any, bitFlag bool, props map[string]any, prefix string) reflect.Type
- func (tr *EnumRegistry) AllTagged(key string) []reflect.Type
- func (tr *EnumRegistry) AltStrings(enumName string) map[int64]string
- func (tr *EnumRegistry) BitFlagsFromStringAltFirst(bflg *int64, str string, et reflect.Type, n int) error
- func (tr *EnumRegistry) Enum(name string) reflect.Type
- func (tr *EnumRegistry) EnumIfaceToAltString(eval any) string
- func (tr *EnumRegistry) EnumInt64ToAltString(ival int64, typnm string) string
- func (tr *EnumRegistry) IsBitFlag(typ reflect.Type) bool
- func (tr *EnumRegistry) NVals(eval any) int64
- func (tr *EnumRegistry) ParType(enumName string) reflect.Type
- func (tr *EnumRegistry) Prop(enumName, propKey string) any
- func (tr *EnumRegistry) Properties(enumName string) map[string]any
- func (tr *EnumRegistry) SetAnyEnumIfaceFromString(eptr any, str string) error
- func (tr *EnumRegistry) SetAnyEnumValueFromString(eval reflect.Value, str string) error
- func (tr *EnumRegistry) SetEnumIfaceFromAltString(eptr any, str string) error
- func (tr *EnumRegistry) SetEnumIfaceFromStringAltFirst(eptr any, str string) error
- func (tr *EnumRegistry) SetEnumValueFromAltString(eval reflect.Value, str string) error
- func (tr *EnumRegistry) SetEnumValueFromStringAltFirst(eval reflect.Value, str string) error
- func (tr *EnumRegistry) SetProp(enumName, propKey string, val any)
- func (tr *EnumRegistry) TypeRegistered(typ reflect.Type) bool
- func (tr *EnumRegistry) TypeValues(et reflect.Type, alt bool) []EnumValue
- func (tr *EnumRegistry) Values(enumName string, alt bool) []EnumValue
- type EnumValue
- type TestFlags
- type Type
- type TypeAndName
- type TypeAndNameList
- type TypeRegistry
- func (tr *TypeRegistry) AddType(obj any, props map[string]any) reflect.Type
- func (tr *TypeRegistry) AllEmbedsOf(embed reflect.Type, inclusive, includeBases bool) []reflect.Type
- func (tr *TypeRegistry) AllImplementersOf(iface reflect.Type, includeBases bool) []reflect.Type
- func (tr *TypeRegistry) AllTagged(key string) []reflect.Type
- func (tr *TypeRegistry) InheritTypeProps(typ reflect.Type) bool
- func (tr *TypeRegistry) Init()
- func (tr *TypeRegistry) Inst(typ reflect.Type) any
- func (tr *TypeRegistry) InstByName(typeName string) any
- func (tr *TypeRegistry) Prop(typ reflect.Type, propKey string) (any, bool)
- func (tr *TypeRegistry) PropByName(typeName, propKey string) (any, bool)
- func (tr *TypeRegistry) Properties(typ reflect.Type, makeNew bool) *map[string]any
- func (tr *TypeRegistry) PropsByName(typeName string, makeNew bool) *map[string]any
- func (tr *TypeRegistry) SetProps(typ reflect.Type, props map[string]any)
- func (tr *TypeRegistry) Type(typeName string) reflect.Type
- func (tr *TypeRegistry) TypeName(typ reflect.Type) string
Constants ¶
const ( // BitFlag is used for AddEnum to indicate that this is a bit flag enum BitFlag = true // NotBitFlag is used for AddEnum to indicate that this is NOT a bit flag enum NotBitFlag = false )
Variables ¶
var KiT_TestFlags = Enums.AddEnumAltLower(TestFlagsN, NotBitFlag, nil, "Test")
var TypesMu sync.RWMutex
TypesMu protects updating of the type registry maps -- main Addtype etc all happens at startup and does not need protection, but property access does. use RLock for read-access to properties, and Lock for write access when adding or changing key / value.
Functions ¶
func AllErrors ¶ added in v1.1.14
AllErrors returns an err as a concatenation of errors (nil if none). no more than maxN are included (typically 10).
func AllFields ¶
func AllFields(typ reflect.Type) []reflect.StructField
AllFields returns a slice list of all the StructField type information for all elemental fields of given type and all embedded types -- returns nil on error (logged)
func AllFieldsN ¶
AllFieldsN returns number of elemental fields in given type
func AllFieldsTypeFunc ¶
func AllFieldsTypeFunc(typ reflect.Type, fun func(typ reflect.Type, field reflect.StructField) bool) bool
AllFieldsTypeFunc calls a function on all the fields of a given struct type, including those on *any* embedded structs that this struct has -- if fun returns false then iteration stops -- overall rval is false if iteration was stopped or there was an error (logged), true otherwise.
func BitFlagsFromString ¶
BitFlagsFromString sets an int64 of bit flags from a string representation of the bits that are set -- en is the number of defined bits, and also provides the type name for looking up strings
func BitFlagsToString ¶
BitFlagsToString converts an int64 of bit flags into a string representation of the bits that are set -- en is the number of defined bits, and also provides the type name for looking up strings
func BitFlagsTypeFromString ¶
BitFlagsTypeFromString sets an int64 of bit flags from a string representation of the bits that are set -- gets enum type and n of defined elements directly
func CloneToType ¶
CloneToType creates a new object of given type, and uses SetRobust to copy an existing value (of perhaps another type) into it -- only expected to work for basic types
func CopyMapRobust ¶ added in v1.1.14
CopyMapRobust robustly copies maps using SetRobust method for the elements.
func CopySliceRobust ¶ added in v1.1.12
CopySliceRobust robustly copies slices using SetRobust method for the elements.
func EmbedImplements ¶ added in v0.9.4
EmbedImplements checks if given type implements given interface, or it embeds a type that does so -- must pass a type constructed like this: reflect.TypeOf((*gi.Node2D)(nil)).Elem() or just reflect.TypeOf(ki.BaseIface())
func EnumBitDepthCheck ¶ added in v0.9.12
EnumBitDepthCheck checks if given type can handle given number of bit flags
func EnumIfaceFromInt64 ¶
EnumIfaceFromInt64 returns an interface{} value which is an enum value of given type (not a pointer to it), set to given integer value
func EnumIfaceFromString ¶
EnumIfaceFromString returns an interface{} value which is an enum value of given type (not a pointer to it), set to given string value -- requires reflect type of enum
func EnumIfaceToInt64 ¶
EnumIfaceToInt64 converts an enum interface{} into an int64 using reflect -- just use int64(eval) when you have the enum value in hand -- this is when you just have a generic interface{}
func EnumIfaceToString ¶
EnumIfaceToString converts an enum interface{} value to its corresponding string value, using fmt.Stringer interface directly -- same effect as calling fmt.Sprintf("%v") but this is slightly faster
func EnumInt64ToString ¶
EnumInt64ToString first converts an int64 to enum of given type, and then converts that to a string value
func EnumMarshalJSON ¶
func EnumMarshalText ¶
func EnumUnmarshalJSON ¶
func EnumUnmarshalText ¶
func FieldByPath ¶
FieldByPath returns field in type or embedded structs within type, by a dot-separated path -- finds field by name for each level of the path, and recurses.
func FieldValueByPath ¶
FieldValueByPath returns field interface in type or embedded structs within type, by a dot-separated path -- finds field by name for each level of the path, and recurses.
func FlatFieldByName ¶
FlatFieldByName returns field in type or embedded structs within type, by name -- native function already does flat version, so this is just for reference and consistency
func FlatFieldInterfaceByName ¶
FlatFieldInterfaceByName finds field in object and embedded objects, by name, returning interface{} to pointer of field, or nil if not found
func FlatFieldInterfaces ¶
FlatFieldInterfaces returns a slice list of all the field interface{} values *as pointers to the field value* (i.e., calling Addr() on the Field Value) for fields of given struct (must pass a pointer to the struct) and any of its embedded structs -- returns nil on error (logged)
func FlatFieldTag ¶
FlatFieldTag returns given tag value in field in type or embedded structs within type, by name -- empty string if not set or field not found
func FlatFieldVals ¶
FlatFieldsVals returns a slice list of all the field reflect.Value's for fields of given struct (must pass a pointer to the struct) and any of its embedded structs -- returns nil on error (logged)
func FlatFieldValueByName ¶
FlatFieldValueByName finds field in object and embedded objects, by name, returning reflect.Value of field -- native version of Value function already does flat find, so this just provides a convenient wrapper
func FlatFields ¶
func FlatFields(typ reflect.Type) []reflect.StructField
FlatFields returns a slice list of all the StructField type information for fields of given type and any embedded types -- returns nil on error (logged)
func FlatFieldsTypeFunc ¶
func FlatFieldsTypeFunc(typ reflect.Type, fun func(typ reflect.Type, field reflect.StructField) bool) bool
FlatFieldsTypeFunc calls a function on all the primary fields of a given struct type, including those on anonymous embedded structs that this struct has, passing the current (embedded) type and StructField -- effectively flattens the reflect field list -- if fun returns false then iteration stops -- overall rval is false if iteration was stopped or there was an error (logged), true otherwise
func FlatFieldsValueFunc ¶
func FlatFieldsValueFunc(stru any, fun func(stru any, typ reflect.Type, field reflect.StructField, fieldVal reflect.Value) bool) bool
FlatFieldsValueFunc calls a function on all the primary fields of a given struct value (must pass a pointer to the struct) including those on anonymous embedded structs that this struct has, passing the current (embedded) type and StructField -- effectively flattens the reflect field list
func HasUpperCase ¶ added in v0.9.11
HasUpperCase returns true if string has an upper-case letter
func IfaceIsNil ¶
IfaceIsNil checks if an interface value is nil -- the interface itself could be nil, or the value pointed to by the interface could be nil -- this checks both, safely gopy:interface=handle
func KindIsBasic ¶
KindIsBasic returns true if the reflect.Kind is a basic type such as Int, Float, etc
func LongTypeName ¶ added in v0.9.8
LongTypeName returns the long, full package-path qualified type name. This is guaranteed to be unique and used for internal storage of several maps to avoid any conflicts. It is also very quick to compute.
func MakeMap ¶
MakeMap makes a map that is actually addressable, getting around the hidden interface{} that reflect.MakeMap makes, by calling UnhideIfaceValue (from ptrs.go)
func MakeOfType ¶
MakeOfType creates a new object of given type with appropriate magic foo to make it usable
func MakePtrValue ¶
MakePtrValue makes a new pointer to the given value, adding an extra level of indirection, and then removing that indirection, resulting in something that is now addressable / assignable -- this is necessary for enums..
func MakeSlice ¶
MakeSlice makes a map that is actually addressable, getting around the hidden interface{} that reflect.MakeSlice makes, by calling UnhideIfaceValue (from ptrs.go)
func MapDeleteAll ¶ added in v1.1.14
func MapDeleteAll(mv any)
MapDeleteAll deletes everything from map
func MapDeleteValue ¶
MapDeleteValue deletes a key-value from the map (set key to a zero value) -- key is already a reflect.Value
func MapElsValueFun ¶
MapElsValueFun calls a function on all the "basic" elements of given map -- iterates over maps within maps (but not structs, slices within maps).
func MapKeyType ¶
MapKeyType returns the type of the key for the given map (which can be a pointer to a map or a direct map) -- just Key() of map type, but using this function makes it more explicit what is going on.
func MapSort ¶
MapSort sorts keys of map either by key or by value, returns those keys as a slice of reflect.Value, as returned by reflect.Value.MapKeys() method
func MapStructElsN ¶
MapStructElsN returns number of elemental fields in given map / struct types
func MapStructElsValueFun ¶
MapStructElsValueFun calls a function on all the "basic" elements of given map or struct -- iterates over maps within maps and fields within structs
func MapValueSort ¶
MapValueSort sorts keys of map by values
func MapValueType ¶
MapValueType returns the type of the value for the given map (which can be a pointer to a map or a direct map) -- just Elem() of map type, but using this function makes it more explicit what is going on.
func NonPtrInterface ¶
NonPtrInterface returns the non-pointer value of an interface
func NonPtrType ¶
NonPtrType returns the non-pointer underlying type
func NonPtrValue ¶
NonPtrValue returns the non-pointer underlying value
func OnePtrInterface ¶
OnePtrInterface returns the pointer value of an interface, if it is possible to get one through Addr()
func OnePtrType ¶
OnePtrType returns a type that is exactly one pointer away from a non-pointer type
func OnePtrUnderlyingValue ¶ added in v0.9.7
OnePtrUnderlyingValue returns a value that is exactly one pointer away from a non-pointer type, and also goes through an interface to find the actual underlying type behind the interface.
func OnePtrValue ¶
OnePtrValue returns a value that is exactly one pointer away from a non-pointer type
func PtrInterface ¶
PtrInterface returns the pointer value of an interface, if it is possible to get one through Addr()
func PtrValue ¶
PtrValue returns the pointer version (Addr()) of the underlying value if the value is not already a Ptr
func Sel ¶
Sel implements the "mute" function from here http://blog.vladimirvivien.com/2014/03/hacking-go-filter-values-from-multi.html provides a way to select a particular return value in a single expression, without having a separate assignment in between -- I just call it "Sel" as I'm unlikely to remember how to type a mu
func SetEnumIfaceFromInt64 ¶
SetEnumIfaceFromInt64 sets enum interface{} value from int64 value -- must pass a pointer to the enum and also needs raw type of the enum as well -- can't get it from the interface{} reliably
func SetEnumIfaceFromString ¶
SetEnumIfaceFromString sets enum value from string -- must pass a *pointer* to the enum item. IMPORTANT: requires the modified stringer go generate utility that generates a FromString method
func SetEnumValueFromInt64 ¶
SetEnumValueFromInt64 sets enum value from int64 value, using a reflect.Value representation of the enum -- does more checking and can get type from value compared to Iface version
func SetEnumValueFromString ¶
SetEnumValueFromString sets enum value from string using reflect.Value IMPORTANT: requires the modified stringer go generate utility that generates a FromString method
func SetFromDefaultTags ¶ added in v1.1.12
SetFromDefaultTags sets values of fields in given struct based on `def:` default value field tags.
func SetMapRobust ¶ added in v0.9.8
SetMapRobust robustly sets a map value using reflect.Value representations of the map, key, and value elements, ensuring that the proper types are used for the key and value elements using sensible conversions. map value must be a valid map value -- that is not checked.
func SetRobust ¶
SetRobust robustly sets the 'to' value from the 'from' value. destination must be a pointer-to. Copies slices and maps robustly, and can set a struct, slice or map from a JSON-formatted string from value. gopy:interface=handle
func SetTypeProp ¶
SetTypeProp provides safe (mutex protected) write setting of property map returned by Properties method -- must use this for all Properties access!
func ShortTypeName ¶ added in v0.9.8
ShortTypeName returns the short version of a package-qualified type name which just has the last element of the path. This is what is used in standard Go programming, and is is used for the key to lookup reflect.Type names -- i.e., this is what you should save in a JSON file. The potential naming conflict is worth the brevity, and typically a given file will only contain mutually-compatible, non-conflicting types. This is cached in ShortNames because the path.Base computation is apparently a bit slow.
func SliceDeleteAt ¶
SliceDeleteAt deletes element at given index from slice
func SliceElType ¶
SliceElType returns the type of the elements for the given slice (which can be a pointer to a slice or a direct slice) -- just Elem() of slice type, but using this function makes it more explicit what is going on. And it uses OnePtrUnderlyingValue to get past any interface wrapping.
func SliceNewAt ¶
SliceNewAt inserts a new blank element at given index in the slice -- -1 means the end
func SliceSort ¶
SliceSort sorts a slice of basic values (see StructSliceSort for sorting a slice-of-struct using a specific field), trying floats.Floater Float(), ints.Inter Int(), interfaces first, and then falling back on reflect.Kind float, int, string conversions (first fmt.Stringer String()) and supporting time.Time directly as well.
func StringJSON ¶ added in v1.1.6
StringJSON returns a JSON representation of item, as a string e.g., for printing / debugging etc.
func StructSliceSort ¶
StructSliceSort sorts a slice of a struct according to the given field indexes and sort direction, trying floats.Floater Float(), ints.Inter Int(), interfaces first, and then falling back on reflect.Kind float, int, string conversions (first fmt.Stringer String()) and supporting time.Time directly as well. There is no direct method for checking the field indexes so those are assumed to be accurate -- will panic if not!
func StructTags ¶
StructTags returns a map[string]string of the tag string from a reflect.StructTag value e.g., from StructField.Tag
func ToFloat ¶
ToFloat robustly converts anything to a Float64 -- uses the floats.Floater Float() interface first if available gopy:interface=handle
func ToFloat32 ¶
ToFloat32 robustly converts anything to a Float32 -- uses the floats.Floater Float() interface first if available gopy:interface=handle
func ToInt ¶
ToInt robustly converts anything to an int64 -- uses the ints.Inter ToInt interface first if available gopy:interface=handle
func ToString ¶
ToString robustly converts anything to a String -- because Stringer is so ubiquitous, and we fall back to fmt.Sprintf(%v) in worst case, this should definitely work in all cases, so there is no bool return value gopy:interface=handle
func ToStringPrec ¶ added in v0.9.8
ToStringPrec robustly converts anything to a String using given precision for converting floating values -- using a value like 6 truncates the nuisance random imprecision of actual floating point values due to the fact that they are represented with binary bits. See ToString for more info. gopy:interface=handle
func TypeEmbeds ¶
TypeEmbeds checks if given type embeds another type, at any level of recursive embedding (including being the type itself)
func TypeFor ¶ added in v1.1.16
TypeFor returns the reflect.Type that represents the type argument T. It is a copy of reflect.TypeFor, which will likely be added in Go 1.22 (see https://github.com/golang/go/issues/60088)
func TypeProp ¶
TypeProp provides safe (mutex protected) read access to property map returned by Properties method -- must use this for all Properties access!
func UnhideIfaceValue ¶
UnhideIfaceValue returns a reflect.Value for any of the Make* functions that is actually assignable -- even though these functions return a pointer to the new object, it is somehow hidden behind an interface{} and this magic code, posted by someone somewhere that I cannot now find again, un-hides it..
func ValueIsZero ¶
ValueIsZero returns true if the reflect.Value is Zero or nil or invalid or otherwise doesn't have a useful value -- from https://github.com/golang/go/issues/7501
Types ¶
type Describer ¶ added in v1.1.16
type Describer interface { // Desc returns a description for an item Desc() string }
Describer interface provides a description for an item, typically to be displayed on hover as a tooltip in a GUI
type EnumRegistry ¶
type EnumRegistry struct { // Enums is a map from the *short* package-qualified name to reflect.Type Enums map[string]reflect.Type // Props contains properties that can be associated with each enum type // e.g., "BitFlag": true, "AltStrings" : map[int64]string, or other custom settings. // The key here is the short package-qualified name Props map[string]map[string]any // Vals contains cached EnumValue representations of the enum values. // Used by Values method. Vals map[string][]EnumValue }
EnumRegistry is a map from an enum-style const int type name to a corresponding reflect.Type and conversion methods generated by (modified) stringer that convert to / from strings.
Each such type must be explicitly registered by calling AddEnum in an expression that also initializes a new global variable that is then useful whenever you need to specify that type:
var KiT_MyEnum = kit.Enums.AddEnum(MyEnumN, bitFlag true/false, TypeNameProps (or nil))
where MyEnum is the name of the type, MyEnumN is the enum value representing the number of defined enums (always good practice to define this value, for ease of extension by others), and TypeNameProps is nil or a map[string]interface{} of properties, OR:
var KiT_MyEnum = kit.Enums.AddEnumAltLower(MyEnumN, bitFlag true/false, TypeNameProps, "Prefix")
which automatically registers alternative names as lower-case versions of const names with given prefix removed -- often what is used in e.g., json or xml kinds of formats.
The resulting type name is registered using a *short* package-qualified version of the type name, with just the last directory name . Type. This is the usual name used in programming Go. All properties are registered using this same short name.
special properties:
* "N": max value of enum defined -- number of enum entries (assuming ordinal, which is all that is currently supported here)
* "BitFlag": true -- each value represents a bit in a set of bit flags, so the string rep of a value contains an or-list of names for each bit set, separated by "|". Use the bitflag package to set and clear bits while keeping the definition of the flags as a standard ordinal integer value -- much more flexible than pre-compiling the bitmasks. Usually should be an int64 type.
* "AltStrings": map[int64]string -- provides an alternative string mapping for the enum values
* "ParType": reflect.Type -- parent type that this extends.
Also recommend defining JSON I/O functions for each registered enum -- much safer to save enums as strings than using their raw numerical values, which can change over time:
func (ev TestFlags) MarshalJSON() ([]byte, error) { return kit.EnumMarshalJSON(ev) } func (ev *TestFlags) UnmarshalJSON() ([]byte, error) { return kit.EnumUnmarshalJSON(ev) }
And any value that will be used as a key in a map must define Text versions (which don't use quotes)
func (ev TestFlags) MarshalText() ([]byte, error) { return kit.EnumMarshalText(ev) } func (ev *TestFlags) UnmarshalText() ([]byte, error) { return kit.EnumUnmarshalText(ev) }
var Enums EnumRegistry
Enums is master registry of enum types -- can also create your own package-specific ones
func (*EnumRegistry) AddEnum ¶
AddEnum adds a given type to the registry -- requires the N value to set N from and grab type info from -- if bitFlag then sets BitFlag property, and each value represents a bit in a set of bit flags, so the string rep of a value contains an or-list of names for each bit set, separated by | -- can also add additional properties -- they are copied so can be re-used across enums
func (*EnumRegistry) AddEnumAltLower ¶
func (tr *EnumRegistry) AddEnumAltLower(en any, bitFlag bool, props map[string]any, prefix string) reflect.Type
AddEnumAltLower adds a given type to the registry -- requires the N value to set N from and grab type info from -- automatically initializes AltStrings alternative string map based on the name with given prefix removed (e.g., a type name-based prefix) and lower-cased -- also requires the number of enums -- assumes starts at 0
func (*EnumRegistry) AddEnumExt ¶ added in v0.9.9
func (tr *EnumRegistry) AddEnumExt(parTyp reflect.Type, en any, bitFlag bool, props map[string]any) reflect.Type
AddEnumExt adds a given type to the registry that extends an existing parTyp enum. Requires the N value to set N from and grab type info from. if bitFlag then sets BitFlag property, and each value represents a bit in a set of bit flags, so the string rep of a value contains an or-list of names for each bit set, separated by | -- can also add additional properties -- they are copied so can be re-used across enums
func (*EnumRegistry) AddEnumExtAltLower ¶ added in v0.9.9
func (tr *EnumRegistry) AddEnumExtAltLower(parTyp reflect.Type, en any, bitFlag bool, props map[string]any, prefix string) reflect.Type
AddEnumExtAltLower adds a given type to the registry that extends an existing parTyp enum. Requires the N value to set N from and grab type info from. Automatically initializes AltStrings alternative string map based on the name with given prefix removed (e.g., a type name-based prefix) and lower-cased. Also requires the number of enums -- assumes starts at end of parent.
func (*EnumRegistry) AllTagged ¶
func (tr *EnumRegistry) AllTagged(key string) []reflect.Type
AllTagged returns a list of all registered enum types that include a given property key value -- does not check for the value of that value -- just its existence
func (*EnumRegistry) AltStrings ¶
func (tr *EnumRegistry) AltStrings(enumName string) map[int64]string
AltStrings returns optional alternative string map for enums -- e.g., lower-case, without prefixes etc -- can put multiple such alt strings in the one string with your own separator, in a predefined order, if necessary, and just call strings.Split on those and get the one you want. Uses short package-qualified name. Returns nil if not set.
func (*EnumRegistry) BitFlagsFromStringAltFirst ¶
func (tr *EnumRegistry) BitFlagsFromStringAltFirst(bflg *int64, str string, et reflect.Type, n int) error
BitFlagsFromStringAltFirst sets an int64 of bit flags from a string representation of the bits that are set, using alt-strings first -- gets enum type and n of defined elements directly
func (*EnumRegistry) Enum ¶
func (tr *EnumRegistry) Enum(name string) reflect.Type
Enum finds an enum type based on its *short* package-qualified type name returns nil if not found.
func (*EnumRegistry) EnumIfaceToAltString ¶
func (tr *EnumRegistry) EnumIfaceToAltString(eval any) string
EnumIfaceToAltString converts an enum interface{} value to its corresponding alternative string value from the enum registry
func (*EnumRegistry) EnumInt64ToAltString ¶
func (tr *EnumRegistry) EnumInt64ToAltString(ival int64, typnm string) string
EnumInt64ToAltString converts an int64 value to the enum of given type, and then into corresponding alternative string value
func (*EnumRegistry) IsBitFlag ¶
func (tr *EnumRegistry) IsBitFlag(typ reflect.Type) bool
IsBitFlag checks if this enum is for bit flags instead of mutually-exclusive int values -- checks BitFlag property -- if true string rep of a value contains an or-list of names for each bit set, separated by |
func (*EnumRegistry) NVals ¶
func (tr *EnumRegistry) NVals(eval any) int64
NVals returns the number of defined enum values for given enum interface
func (*EnumRegistry) ParType ¶ added in v0.9.9
func (tr *EnumRegistry) ParType(enumName string) reflect.Type
ParType returns optional parent type that given type extends -- nil if not set.
func (*EnumRegistry) Prop ¶
func (tr *EnumRegistry) Prop(enumName, propKey string) any
Prop safely finds an enum type property from short package-qualified name and property key. Returns nil if not found.
func (*EnumRegistry) Properties ¶
func (tr *EnumRegistry) Properties(enumName string) map[string]any
Props returns properties for this type based on short package-qualified name. Makes props map if not already made.
func (*EnumRegistry) SetAnyEnumIfaceFromString ¶
func (tr *EnumRegistry) SetAnyEnumIfaceFromString(eptr any, str string) error
SetAnyEnumIfaceFromString looks up enum type on registry, and if it is registered as a bitflag, sets bits from string, otherwise tries to set from alt strings if those exist, and finally tries direct set from string -- must pass a *pointer* value to the enum item.
func (*EnumRegistry) SetAnyEnumValueFromString ¶
func (tr *EnumRegistry) SetAnyEnumValueFromString(eval reflect.Value, str string) error
SetAnyEnumValueFromString looks up enum type on registry, and if it is registered as a bitflag, sets bits from string, otherwise tries to set from alt strings if those exist, and finally tries direct set from string -- must pass a *pointer* value to the enum item.
func (*EnumRegistry) SetEnumIfaceFromAltString ¶
func (tr *EnumRegistry) SetEnumIfaceFromAltString(eptr any, str string) error
SetEnumIfaceFromAltString sets from alternative string list using an interface{} to the enum -- must pass a *pointer* to the enum item.
func (*EnumRegistry) SetEnumIfaceFromStringAltFirst ¶
func (tr *EnumRegistry) SetEnumIfaceFromStringAltFirst(eptr any, str string) error
SetEnumIfaceFromStringAltFirst first attempts to set an enum from an alternative string, and if that fails, then it tries to set from the regular string representation func (tr *EnumRegistry)
func (*EnumRegistry) SetEnumValueFromAltString ¶
func (tr *EnumRegistry) SetEnumValueFromAltString(eval reflect.Value, str string) error
SetEnumValueFromAltString sets value from alternative string using a reflect.Value -- must pass a *pointer* value to the enum item.
func (*EnumRegistry) SetEnumValueFromStringAltFirst ¶
func (tr *EnumRegistry) SetEnumValueFromStringAltFirst(eval reflect.Value, str string) error
SetEnumValueFromStringAltFirst first attempts to set an enum from an alternative string, and if that fails, then it tries to set from the regular string representation func (tr *EnumRegistry)
func (*EnumRegistry) SetProp ¶ added in v0.9.9
func (tr *EnumRegistry) SetProp(enumName, propKey string, val any)
SetProp safely sets given property for given enum name
func (*EnumRegistry) TypeRegistered ¶
func (tr *EnumRegistry) TypeRegistered(typ reflect.Type) bool
TypeRegistered returns true if the given type is registered as an enum type.
func (*EnumRegistry) TypeValues ¶
func (tr *EnumRegistry) TypeValues(et reflect.Type, alt bool) []EnumValue
TypeValues returns an EnumValue slice for all the values of an enum type -- if alt is true and alt names exist, then those are used
type EnumValue ¶
type EnumValue struct { // name for this value Name string `desc:"name for this value"` // integer value Value int64 `desc:"integer value"` // the enum type that this value belongs to Type reflect.Type `desc:"the enum type that this value belongs to"` // the comment description of the enum value Desc string `desc:"the comment description of the enum value"` }
EnumValue represents enum values, in common int64 terms, e.g., for GUI
type TestFlags ¶
type TestFlags int32
TestFlags are for testing -- need the generated string code, so putting in here
func (*TestFlags) FromString ¶
func (TestFlags) MarshalJSON ¶
func (*TestFlags) UnmarshalJSON ¶
type Type ¶
Type provides JSON, XML marshal / unmarshal with encoding of underlying type name using kit.Types type name registry
func (Type) MarshalJSON ¶
MarshalJSON saves only the type name
func (Type) MarshalXML ¶
MarshalXML saves only the type name
func (Type) ShortTypeName ¶ added in v0.9.8
ShortTypeName returns short package-qualified name of the type: package dir + "." + type name
func (*Type) UnmarshalJSON ¶
UnmarshalJSON loads the type name and looks it up in the Types registry of type names
func (*Type) UnmarshalXML ¶
UnmarshalXML loads the type name and looks it up in the Types registry of type names
type TypeAndName ¶
a type and a name -- useful for specifying configurations of children in Ki nodes, and various other use-cases
type TypeAndNameList ¶
type TypeAndNameList []TypeAndName
list of type-and-names -- can be created from a string spec
func (*TypeAndNameList) SetFromString ¶
func (t *TypeAndNameList) SetFromString(str string) error
construct a type-and-name list from a list of type name pairs, space separated -- can include any json-like { } , [ ] formatting which is all stripped away and just the pairs of names are used
type TypeRegistry ¶
type TypeRegistry struct { // Types is a map from the *short* package qualified name to reflect.Type Types map[string]reflect.Type // ShortNames is a map of short package qualified names keyed by // the long, fully unambiguous package path qualified name. // It is somewhat expensive to compute this short name, so // caching it is faster ShortNames map[string]string // Props are type properties -- nodes can get default properties from // their types and then optionally override them with their own settings. // The key here is the long, full type name. Props map[string]map[string]any // Insts contain an instance of each type (the one passed during AddType) // The key here is the long, full type name. Insts map[string]any }
TypeRegistry contains several maps where properties of types are maintained for general usage.
See also EnumRegistry for a version specifically for "enum" types (const int types that associate a name with an int value).
Each type must be explicitly registered by calling AddType in an expression that also initializes a new global variable that is then useful whenever you need to specify that type, e.g., when adding a new Node in the Ki system.
var KiT_MyType = ki.Types.AddType(&MyType{}, [props|nil])
where MyType is the type -- note that it is ESSENTIAL to pass a pointer so that the type is considered addressable, even after we get Elem() of it.
props is a map[string]interface{} of optional properties that can be associated with the type -- this is used in the GoGi graphical interface system for example to configure menus and toolbars for different types.
Once registered, the reflect.Type can be looked up via the usual *short* package-qualified type name that you use in programming (e.g., kit.TypeRegistry) -- this is maintained in the Types map. This lookup enables e.g., saving type name information in JSON files and then using that type name to create an object of that type upon loading.
The Props map stores the properties (which can be updated during runtime as well), and Insts also stores an interface{} pointer to each type that has been registered.
var Types TypeRegistry
Types is master registry of types that embed Ki Nodes
func (*TypeRegistry) AddType ¶
AddType adds a given type to the registry -- requires an empty object to grab type info from (which is then stored in Insts) -- must be passed as a pointer to ensure that it is an addressable, settable type -- also optional properties that can be associated with the type and accessible e.g. for view-specific properties etc -- these props MUST be specific to this type as they are used directly, not copied!!
func (*TypeRegistry) AllEmbedsOf ¶
func (tr *TypeRegistry) AllEmbedsOf(embed reflect.Type, inclusive, includeBases bool) []reflect.Type
AllEmbedsOf returns a list of all registered types that embed (inherit from in C++ terminology) the given type -- inclusive determines whether the type itself is included in list -- includeBases indicates whether to include types marked with property of base-type -- typically not useful for user-facing type selection
func (*TypeRegistry) AllImplementersOf ¶
AllImplementersOf returns a list of all registered types that implement the given interface type at any level of embedding -- must pass a type constructed like this: kit.TypeFor[gi.Node2D]() -- includeBases indicates whether to include types marked with property of base-type -- typically not useful for user-facing type selection
func (*TypeRegistry) AllTagged ¶
func (tr *TypeRegistry) AllTagged(key string) []reflect.Type
AllTagged returns a list of all registered types that include a given property key value -- does not check for the value of that value -- just its existence
func (*TypeRegistry) InheritTypeProps ¶ added in v0.9.9
func (tr *TypeRegistry) InheritTypeProps(typ reflect.Type) bool
InheritTypeProps attempts to inherit certain heritable type properties from first embedded type. Returns true if did.
func (*TypeRegistry) Init ¶
func (tr *TypeRegistry) Init()
Init initializes the type registry, including adding basic types
func (*TypeRegistry) Inst ¶
func (tr *TypeRegistry) Inst(typ reflect.Type) any
Inst returns the interface{} instance of given type (it is a pointer to that type). Returns nil if not found.
func (*TypeRegistry) InstByName ¶
func (tr *TypeRegistry) InstByName(typeName string) any
InstByName returns the interface{} instance of given type (it is a pointer to that type) using the long, unambiguous package-qualified name. Returns nil if not found.
func (*TypeRegistry) Prop ¶
Prop safely finds a type property from type and property key -- returns false if not found.
func (*TypeRegistry) PropByName ¶
func (tr *TypeRegistry) PropByName(typeName, propKey string) (any, bool)
PropByName safely finds a type property from type name (using the long, unambiguous package-qualified name) and property key. Returns false if not found
func (*TypeRegistry) Properties ¶
Properties returns properties for given type. It optionally makes props map for this type if not already made. Can use this to register properties for types that are not registered.
func (*TypeRegistry) PropsByName ¶
func (tr *TypeRegistry) PropsByName(typeName string, makeNew bool) *map[string]any
PropsByName returns properties for given type name, using the long, unambiguous package-qualified name. It optionally makes props map for this type if not already made. Can use this to register properties for types that are not registered.
func (*TypeRegistry) SetProps ¶
func (tr *TypeRegistry) SetProps(typ reflect.Type, props map[string]any)
SetProps sets the type props for given type, uses write mutex lock