一次检查golang中的所有数据键

我有以下代码:


type DisplayObject struct {

    ID      string `json:"id,omitempty" bson:"id"`

    URI     string `json:"uri,omitempty" bson:"uri"`

    Display string `json:"display,omitempty" bson:"display"`

}


if DisplayObject.ID != "" {

    // do something

}


if DisplayObject.URI != "" {

    // do something

}


if DisplayObject.Display != "" {

    // do something

}

在javascript中我会做


for (var key in DisplayObject) {

  if (DisplayObject.hasOwnProperty(key)) {

    // do something

  }

}

如何通过 go 中的对象完成 for 循环?


catspeake
浏览 152回答 2
2回答

慕妹3242003

你可以使用反射来完成这样的事情:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "reflect")type DisplayObject struct {&nbsp; &nbsp; ID&nbsp; &nbsp; &nbsp; string `json:"id,omitempty" bson:"id"`&nbsp; &nbsp; URI&nbsp; &nbsp; &nbsp;string `json:"uri,omitempty" bson:"uri"`&nbsp; &nbsp; Display string `json:"display,omitempty" bson:"display"`}func main() {&nbsp; &nbsp; displayObj := &DisplayObject{ID: "foo"}&nbsp; &nbsp; s := reflect.ValueOf(displayObj).Elem()&nbsp; &nbsp; for i := 0; i < s.NumField(); i++ {&nbsp; &nbsp; &nbsp; &nbsp; fieldName := s.Type().Field(i).Name&nbsp; &nbsp; &nbsp; &nbsp; fieldValue := s.Field(i).String()&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s: %s\n", fieldName, fieldValue)&nbsp; &nbsp; &nbsp; &nbsp; // do something with the field data&nbsp; &nbsp; }}

MM们

您正在尝试比较无与伦比。Javascript 对象类似于 map[string]interface{} 。在您的情况下也可以是 map[string]string,对于地图,您可以使用 len(m) == 0。结构是更快的容器,但不太灵活的容器。您不能更改成员的数量或类型。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go