github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/utils/lists/generics.go (about)

     1  package lists
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/lmorg/murex/lang/types"
     7  )
     8  
     9  // GenericToString converts []interface to []string
    10  func GenericToString(list interface{}) ([]string, error) {
    11  	switch t := list.(type) {
    12  	case []string:
    13  		return t, nil
    14  
    15  	case []any:
    16  		new := make([]string, len(t))
    17  		for i := range t {
    18  			v, err := types.ConvertGoType(t[i], types.String)
    19  			if err != nil {
    20  				return nil, fmt.Errorf("cannot convert element %d: %s", i, err.Error())
    21  			}
    22  			new[i] = v.(string)
    23  		}
    24  		return new, nil
    25  
    26  	default:
    27  		return nil, fmt.Errorf("expecting []string or []any, instead got %T", t)
    28  	}
    29  }