github.com/goki/ki@v1.1.11/kit/typeandname.go (about)

     1  // Copyright (c) 2018, The GoKi Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package kit
     6  
     7  import (
     8  	"fmt"
     9  	"reflect"
    10  	"strings"
    11  )
    12  
    13  // a type and a name -- useful for specifying configurations of children in Ki
    14  // nodes, and various other use-cases
    15  type TypeAndName struct {
    16  	Type reflect.Type
    17  	Name string
    18  }
    19  
    20  // list of type-and-names -- can be created from a string spec
    21  type TypeAndNameList []TypeAndName
    22  
    23  // 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
    24  func (t *TypeAndNameList) SetFromString(str string) error {
    25  	str = strings.Replace(str, ",", " ", -1)
    26  	str = strings.Replace(str, "{", " ", -1)
    27  	str = strings.Replace(str, "}", " ", -1)
    28  	str = strings.Replace(str, "[", " ", -1)
    29  	str = strings.Replace(str, "]", " ", -1)
    30  	ds := strings.Fields(str) // split by whitespace
    31  	sz := len(ds)
    32  	for i := 0; i < sz; i += 2 {
    33  		tn := ds[i]
    34  		nm := ds[i+1]
    35  		typ := Types.Type(tn)
    36  		if typ == nil {
    37  			return fmt.Errorf("TypeAndNameList SetFromString: Types type name not found: %v", tn)
    38  		}
    39  		(*t) = append(*t, TypeAndName{typ, nm})
    40  	}
    41  	return nil
    42  }
    43  
    44  func (t *TypeAndNameList) Add(typ reflect.Type, nm string) {
    45  	(*t) = append(*t, TypeAndName{typ, nm})
    46  }