From: cuishuang Date: Tue, 3 Feb 2026 17:44:07 +0000 (+0800) Subject: reflect: add examples for Value.Fields and Value.Methods X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=31768104cbe710d2358d5da34b4c223ad3ff2c6f;p=gostls13.git reflect: add examples for Value.Fields and Value.Methods Change-Id: Ibfdc79d94f5406e2e387b75163f26d2ab0f207f9 Reviewed-on: https://go-review.googlesource.com/c/go/+/741580 Reviewed-by: Junyang Shao Reviewed-by: Ian Lance Taylor LUCI-TryBot-Result: Go LUCI Auto-Submit: Ian Lance Taylor Reviewed-by: Michael Pratt --- diff --git a/src/reflect/example_test.go b/src/reflect/example_test.go index bcc2303766..1df524758a 100644 --- a/src/reflect/example_test.go +++ b/src/reflect/example_test.go @@ -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 +}