dongmingxiang0312 2015-06-18 10:58
浏览 58
已采纳

如何按字母顺序对结构字段排序

How could I get an output of struct, sorted by fields?

type T struct {
    B int
    A int
}

t := &T{B: 2, A: 1}

doSomething(t)

fmt.Println(t)  // &{1 2} --> Sorted by fields
  • 写回答

2条回答 默认 最新

  • douqiang6448 2015-06-18 12:15
    关注

    A struct is an ordered collection of fields. The fmt package uses reflection to get the fields and values of a struct value, and generates output in the order in which they were defined.

    So the simplest solution would be to declare your type where you already have your fields arranged in alphabetical order:

    type T struct {
        A int
        B int
    }
    

    If you can't modify the order of fields (e.g. memory layout is important), you can implement the Stringer interface by specifying a String() method for your struct type:

    func (t T) String() string {
        return fmt.Sprintf("{%d %d}", t.A, t.B)
    }
    

    The fmt package checks if the passed value implements Stringer, and if it does, calls its String() method to generate the output.

    Cons of this solution is that this is not flexible (e.g. if you add a new field, you have to update the String() method too), also you have to do it for every struct type you want it to work (and you can't define methods for types defined in other packages).

    The completely flexible solution can use reflection. You can get the names of fields, sort them by name, and then iterate over the sorted names and get the field values (by name).

    Pros of this solution is that this works for any struct, and it keeps working without modification even if you add or remove fields from your structs. It also works for fields of any type, not just for int fields.

    Here is an example how to do it (try it on the Go Playground):

    func printFields(st interface{}) string {
        t := reflect.TypeOf(st)
    
        names := make([]string, t.NumField())
        for i := range names {
            names[i] = t.Field(i).Name
        }
        sort.Strings(names)
    
        v := reflect.ValueOf(st)
        buf := &bytes.Buffer{}
        buf.WriteString("{")
        for i, name := range names {
            val := v.FieldByName(name)
            if !val.CanInterface() {
                continue
            }
            if i > 0 {
                buf.WriteString(" ")
            }
            fmt.Fprintf(buf, "%v", val.Interface())
        }
        buf.WriteString("}")
    
        return buf.String()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧