1. 程式人生 > >map,struct互轉

map,struct互轉

判斷某個值是否在某個切片中

/**
@func:          判斷某個值是否在某個切片中
@param:
    val:        要查詢的值
    slice:      尋找的切片
@return
    int         查詢到的下標,如果沒有找到返回-1
    error       錯誤資訊
*/
func inSlice(val interface{},slice interface{}) (int,error){
	//先將interface型別的slice轉換為[]interface{}型別的slice1
	valof := reflect.ValueOf
(slice) if valof.Kind() != reflect.Slice { return -1,errors.New("型別錯誤") } slice1 := make([]interface{},0) for i := 0 ; i < valof.Len() ; i++ { slice1 = append(slice1, valof.Index(i).Interface()) } for i,v := range slice1{ if v == val { return i,nil } } return -1,errors.New("not found"
) }

結構體轉Map

/*
@func:                  struct轉map
@param:
    structure:          需要轉換的結構體
    res:                轉換後的map[string]interface{}
    recur:              是否遞迴轉換(是否將內部巢狀的struct也轉換為map)
@return
    error       錯誤資訊
    
結構體的tag的key為map
 */
func StructToMap(structure interface{},res map
[string]interface{},recur bool) error{ //檢查是否為結構體 tp := reflect.TypeOf(structure) v := reflect.ValueOf(structure) switch tp.Kind() { case reflect.Struct: default: return errors.New("所需引數為struct型別,卻傳入"+tp.Kind().String()+"型別") } //res := make(map[string]interface{}) num := tp.NumField() for i := 0; i < num ; i++ { key := tp.Field(i).Name tag := tp.Field(i).Tag.Get("map") if tag != "" && len(tag) != 0 { key = tag } //private型別的不能獲取到值,所以直接排除private的欄位 if v.Field(i).CanInterface() { res[key] = v.Field(i).Interface() //----------------是否繼續解析內層strcut------------- if recur { ztp := reflect.TypeOf(v.Field(i).Interface()) //內層依然是一個struct,那麼遞迴呼叫這個函式 if ztp.Kind() == reflect.Struct{ resMap := make(map[string]interface{}) err := StructToMap(v.Field(i).Interface(),resMap,recur) if err != nil { res[key] = "" return err }else { res[key] = resMap } } } //------------------------------- }else { continue } } return nil }

map轉struct

/*
@func           將map轉為Struct
@param
    mmap        需要轉換的map[string]interface
    structure   轉換後的結構體指標
@return
    error       錯誤資訊

    暫不支援遞迴轉換
*/
func MapToStruct(mmap map[string]interface{},structure interface{}) (err error){
	defer func() {
		if errs := recover(); errs!= nil {
			err = errors.New("調用出錯")
		}
	}()
	ptp := reflect.TypeOf(structure)
	pv := reflect.ValueOf(structure)
	switch ptp.Kind() {
	case reflect.Ptr:
		if ptp.Elem().Kind() == reflect.Struct {
			fmt.Println("sss")
			break
		}else{
			return errors.New("需要*struct型別,卻傳入*"+ptp.Elem().Kind().String()+"型別")
		}
	default:
		return errors.New("需要*struct型別,卻傳入"+ptp.Kind().String()+"型別")
	}
	tp := ptp.Elem()
	v := pv.Elem()
	num := tp.NumField()
	for i := 0 ; i < num ; i++ {
		name := tp.Field(i).Name
		tag := tp.Field(i).Tag.Get("map")
		if len(tag) != 0 {
			name = tag
		}
		value,ok := mmap[name]
		if !ok {
			continue
		}
		//能夠設定值,且型別相同
		if v.Field(i).CanSet(){
			if v.Field(i).Type() == reflect.TypeOf(value){
				v.Field(i).Set(reflect.ValueOf(value))
			}else{
				continue
			}
		}else {
			continue
		}
	}
	return nil
}

生成隨機數

type RandType int64
const (
	RtNum RandType = 1 << iota
	RtLowAlpha
	RtUpAlpha
	RtPunct
)
func (r RandType)String()string{
	str := ""
	switch {
	case r & RtNum == RtNum:
		str += " 數字隨機碼 "
		fallthrough
	case r & RtLowAlpha == RtLowAlpha:
		str += " 小寫字母隨機碼 "
		fallthrough
	case r & RtUpAlpha == RtUpAlpha :
		str += " 大寫字母隨機碼 "
		fallthrough
	case r & RtPunct == RtPunct:
		str += " 符號隨機碼 "
	default:
		str = " 未定義的型別 "

	}
	return  str
}

func RandomStr(ty RandType,width int)string{
	str := ""
	switch {
	case ty & RtNum == RtNum:
		str += "0123456789"
		fallthrough
	case ty & RtLowAlpha == RtLowAlpha:
		str += "abcdefghijklmnopqrstuvwxyz"
		fallthrough
	case ty & RtUpAlpha == RtUpAlpha:
		str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
		fallthrough
	case ty & RtPunct == RtUpAlpha:
		str += ",./;'[][email protected]#$%^&*()`~"
	default:
		str += "ABDEFGHIJKMNQRTUWY123456789abdefghijkmnqrtuwy"
	}
	rand.Seed(time.Now().Unix())
	idx := rand.Int() % len(str)
	res := ""
	for i := 0 ; i < width ; i++ {
		res += str[idx:idx+1]
	}
	return res
}

Urlencode

func Urlencode(url string) string{
	res := base64.URLEncoding.EncodeToString([]byte(url))
	res = strings.Replace(res,"+","%2B",-1)
	res = strings.Replace(res," ","%20",-1)
	res = strings.Replace(res,"/","%2F",-1)
	res = strings.Replace(res,"?","%3F",-1)
	res = strings.Replace(res,"%","%25",-1)
	res = strings.Replace(res,"#","%23",-1)
	res = strings.Replace(res,"&","%26",-1)
	res = strings.Replace(res,"=","%3D",-1)
	return res
}