我想按動態欄位對結構陣列進行排序。這是結構
type user struct{
Name string `json:"name"`
Age int `json:"age"`
Status int `json:"status "`
Type string `json:"type"`
}
這是一個結構陣列
var UserArray []user
我必須按給定的欄位對這個陣列進行排序,該欄位可以是用戶結構的任何欄位。但我將從 UI 接收該排序欄位作為 JSON 標記。像下面
sort := agnutil.GetQueryParamString(<json tag>, "sort", 0, "name")
我已經嘗試過 golang 中的 sort 函式,但是如何動態使用它??
sort.Slice(UserArray , func(i, j int) bool {
return UserArray[i].<givenfield> < UserArray[j].<givenfield>
})
uj5u.com熱心網友回復:
我想嘗試通過欄位的 json 標簽對一段結構進行排序,這是我最終得到的,以防它對任何人有幫助:
package main
import (
"fmt"
"reflect"
"sort"
)
func sortBy(jsonField string, arr []num) {
if len(arr) < 1 {
return
}
// first we find the field based on the json tag
valueType := reflect.TypeOf(arr[0])
var field reflect.StructField
for i := 0; i < valueType.NumField(); i {
field = valueType.Field(i)
if field.Tag.Get("json") == jsonField {
break
}
}
// then we sort based on the type of the field
sort.Slice(arr, func(i, j int) bool {
v1 := reflect.ValueOf(arr[i]).FieldByName(field.Name)
v2 := reflect.ValueOf(arr[j]).FieldByName(field.Name)
switch field.Type.Name() {
case "int":
return int(v1.Int()) < int(v2.Int())
case "string":
return v1.String() < v2.String()
case "bool":
return !v1.Bool() // return small numbers first
default:
return false // return unmodified
}
})
fmt.Printf("\nsort by %s:\n", jsonField)
prettyPrint(arr)
}
func prettyPrint(arr []num) {
for _, v := range arr {
fmt.Printf("% v\n", v)
}
}
type num struct {
Id int `json:"id"`
Name string `json:"name"`
Big bool `json:"big"`
}
func main() {
userArray := []num{
{1, "one", false},
{5, "five", false},
{40, "fourty", true},
{9, "nine", false},
{60, "sixty", true},
}
fmt.Println("original:")
prettyPrint(userArray)
sortBy("id", userArray[:])
sortBy("name", userArray[:])
sortBy("big", userArray[:])
}
original:
{Id:1 Name:one Big:false}
{Id:5 Name:five Big:false}
{Id:40 Name:fourty Big:true}
{Id:9 Name:nine Big:false}
{Id:60 Name:sixty Big:true}
sort by id
{Id:1 Name:one Big:false}
{Id:5 Name:five Big:false}
{Id:9 Name:nine Big:false}
{Id:40 Name:fourty Big:true}
{Id:60 Name:sixty Big:true}
sort by name
{Id:5 Name:five Big:false}
{Id:40 Name:fourty Big:true}
{Id:9 Name:nine Big:false}
{Id:1 Name:one Big:false}
{Id:60 Name:sixty Big:true}
sort by big
{Id:1 Name:one Big:false}
{Id:9 Name:nine Big:false}
{Id:5 Name:five Big:false}
{Id:40 Name:fourty Big:true}
{Id:60 Name:sixty Big:true}
uj5u.com熱心網友回復:
問題有兩個部分:查找給定 JSON 名稱的欄位和按欄位排序。
讓我們從第二部分的代碼開始,按欄位名稱對切片進行排序。這是一個對任何結構型別的結構切片或指向結構的指標切片進行排序的函式。詳情見評論。
// sortByField sorts slice by the named field.
// The slice argument must be a slice of struct or
// a slice of pointer to struct.
func sortByField(slice interface{}, fieldName string) error {
v := reflect.ValueOf(slice)
if v.Kind() != reflect.Slice {
return fmt.Errorf("got %T, expected slice", slice)
}
// Get slice element type.
t := v.Type().Elem()
// Handle pointer to struct.
indirect := t.Kind() == reflect.Ptr
if indirect {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return fmt.Errorf("got %T, expected slice of struct or pointer to struct", slice)
}
// Find the field.
sf, ok := t.FieldByName(fieldName)
if !ok {
return fmt.Errorf("field name %s not found", fieldName)
}
// Create a less function based on the field's kind.
var less func(a, b reflect.Value) bool
switch sf.Type.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
case reflect.Float32, reflect.Float64:
less = func(a, b reflect.Value) bool { return a.Float() < b.Float() }
case reflect.String:
less = func(a, b reflect.Value) bool { return a.String() < b.String() }
case reflect.Bool:
less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() }
default:
return fmt.Errorf("field type %s not supported", sf.Type)
}
// Sort it!
sort.Slice(slice, func(i, j int) bool {
a := v.Index(i)
b := v.Index(j)
if indirect {
a = a.Elem()
b = b.Elem()
}
a = a.FieldByIndex(sf.Index)
b = b.FieldByIndex(sf.Index)
return less(a, b)
})
return nil
}
將 JSON 名稱映射到欄位很復雜。在一般情況下,程式需要處理以下內容:通過嵌入提升的欄位和出現的任何沖突、不區分大小寫、省略 JSON 名稱等。 這是處理問題中簡單情況的函式:
func simpleJSONToFieldName(t reflect.Type, name string) (string, bool) {
for i := 0; i < t.NumField(); i {
sf := t.Field(i)
n := strings.Split(sf.Tag.Get("json"), ",")[0]
if n == name {
return sf.Name, true
}
}
return "", false
}
以下是如何將它們組合在一起:
var UserArray []user
jsonName := request.FormValue("sort")
fieldName, ok := simpleJSONToFieldName(reflect.TypeOf(user{}), jsonName)
if !ok {
// TODO: handle bad input
}
if err := sortByField(UserArray, fieldName); err != nil {
// TODO: handle error
}
Run an example on the playground.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/351245.html
上一篇:我想在陣列中找到唯一的重復值,但我沒有得到下面是我在Java中的代碼
下一篇:根據類別級別排序
