-2

I have value [token code id_token] from map, value of map type []interface{}

resp := result["response_types"]

resp is type []interface{}.

i need to convert it to: clientobj.ResponseTypes

type client struct{
    ResponseTypes sqlxx.StringSlicePipeDelimiter `json:"response_types" db:"response_types"`
}

in package sqlxx

package sqlxx
type StringSlicePipeDelimiter []string

is there is to convert it?

asmmo
  • 6,922
  • 1
  • 11
  • 25
isra
  • 11
  • please open this question, that question not duplicate. I solve it by marshal and unmarshal .I want to share my answer. – isra Feb 09 '21 at 13:29

1 Answers1

2

To convert a []inteface{} to []string, you just iterate over the slice and use type assertions:

// given resp is []interface{}
// using make and len of resp for capacity to allocate the memory in one go
// instead of having the runtime reallocate memory several times when calling append
str := make([]string, 0, len(resp))
for _, v := range resp {
    if s, ok := v.(string); ok {
        str = append(str, s)
    }
}

The real question here is how you end up with a variable of type []interface{} in the first place. Is there no way for you to avoid it? Looking at the StringSlicePipeDelimiter type itself, it has the Scan method (part of the interface required to scan values from the database into the type) right here, so I can't help but wonder why you're using an intermittent variable of type []interface{}

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • I'm use intermittent variable of type []interface{} because I get data from Aerospike data – isra Feb 08 '21 at 12:05
  • that it returned as type of aerospike.BinMap , result["response_types"] is returned value as []interface{} that I need to convert it to StringSlicePipeDelimiter. – isra Feb 08 '21 at 12:13