程式設計師如何透過讓欄位按字母順序出現來產生結構化資料輸出?具體來說,請考慮以下內容:
type T struct { B int A int } t := &T{B: 2, A: 1} doSomething(t) fmt.Println(t) // Desired output: &{1 2} — Fields sorted alphabetically
透過欄位排序的解決方案:
預設情況下,結構體保留聲明的欄位順序。因此,透過使用所需的字段序列重新定義結構體,可以獲得輸出:
type T struct { A int B int }
透過Stringer 介面解決方案:
另一種方法涉及實作Stringer結構體的介面:
func (t T) String() string { return fmt.Sprintf("{%d %d}", t.A, t.B) }
fmt 套件檢查Stringer 實作並利用它的String()方法用於生成輸出。
透過反射的解決方案:
為了跨結構體的彈性,可以利用反射。可以取得欄位名稱、排序並檢索其對應的值。
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() }
以上是程式設計師如何在 Go 中按字母順序排列結構體欄位輸出?的詳細內容。更多資訊請關注PHP中文網其他相關文章!