]> Cypherpunks repositories - gostls13.git/commitdiff
reflect: add examples for Value.Fields and Value.Methods
authorcuishuang <imcusg@gmail.com>
Tue, 3 Feb 2026 17:44:07 +0000 (01:44 +0800)
committerGopher Robot <gobot@golang.org>
Thu, 12 Feb 2026 18:32:29 +0000 (10:32 -0800)
Change-Id: Ibfdc79d94f5406e2e387b75163f26d2ab0f207f9
Reviewed-on: https://go-review.googlesource.com/c/go/+/741580
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Michael Pratt <mpratt@google.com>
src/reflect/example_test.go

index bcc2303766e87e992d156c50694eb2cca0cabff8..1df524758ab66f83d1132a6fcfbb70368309a32c 100644 (file)
@@ -206,3 +206,57 @@ func ExampleValue_FieldByName() {
        // Output:
        // Name: John
 }
+
+func ExampleValue_Fields() {
+       type Person struct {
+               Name    string
+               Age     int
+               City    string
+               Country string
+       }
+
+       p := Person{Name: "Alice", Age: 30, City: "New York", Country: "USA"}
+       v := reflect.ValueOf(p)
+
+       fmt.Println("Iterating over all struct fields:")
+       for field, value := range v.Fields() {
+               fmt.Printf("  %s = %v\n", field.Name, value)
+       }
+
+       // Output:
+       // Iterating over all struct fields:
+       //   Name = Alice
+       //   Age = 30
+       //   City = New York
+       //   Country = USA
+}
+
+func ExampleValue_Methods() {
+       r := bytes.NewReader([]byte("hello"))
+       v := reflect.ValueOf(r)
+
+       fmt.Println("Methods of *bytes.Reader:")
+       for method, methodValue := range v.Methods() {
+               fmt.Printf("  %s\n", method.Name)
+               // Call the Len method as an example
+               if method.Name == "Len" {
+                       result := methodValue.Call(nil)
+                       fmt.Printf("  Len() = %v\n", result[0])
+               }
+       }
+
+       // Output:
+       // Methods of *bytes.Reader:
+       //   Len
+       //   Len() = 5
+       //   Read
+       //   ReadAt
+       //   ReadByte
+       //   ReadRune
+       //   Reset
+       //   Seek
+       //   Size
+       //   UnreadByte
+       //   UnreadRune
+       //   WriteTo
+}