Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: reflect: Add Type.Fields() iter.Seq[StructField] and Type.Methods() iter.Seq[Method] #66631

Open
earthboundkid opened this issue Apr 1, 2024 · 6 comments
Labels
Milestone

Comments

@earthboundkid
Copy link
Contributor

Proposal Details

reflect.Type.Fields() iter.Seq[StructField] and reflect.Type.Methods() iter.Seq[Method] would be more convenient than having to call i := range myType.NumFields() and myType.Field(i) etc.

You could also add iterators to reflect.Value as well but those are less obviously useful. Probably worth doing just for completeness though.

@gopherbot gopherbot added this to the Proposal milestone Apr 1, 2024
@thediveo
Copy link

thediveo commented Apr 1, 2024

could this be a duplicate of #66626?

@adonovan
Copy link
Member

adonovan commented Apr 1, 2024

could this be a duplicate of #66626?

No, that issue relates to the go/types package, not reflect.

@thediveo
Copy link

thediveo commented Apr 1, 2024

ah, overlooked this crucial detail, thank you!

@earthboundkid
Copy link
Contributor Author

This was in fact inspired by #66626, but yes, it is for reflect, not types.

@adonovan
Copy link
Member

adonovan commented Apr 2, 2024

Alternatively, the method value could be the iterator as opposed to returning an iterator, like so:

package reflect

type Type interface {
	...
	// Fields is a go1.23 iterator over all the fields of a struct type (etc).
	//
	// Example: for ftype := range t.Fields { ... }
	Fields(yield func(ftype *Func) bool)
}

func (t *rtype) Fields(yield func(ftype *Func) bool) {
	for i := range t.NumFields() {
		if !yield(t.Field(i)) {
			break
		}
	}
}
// client code
var t reflect.Type = ...
for ftype := range t.Fields { ... }

@earthboundkid
Copy link
Contributor Author

Maybe. That keeps from introducing an import dependency we might not want, but it goes against the general conventions used elsewhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Incoming
Development

No branches or pull requests

4 participants