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 TypeByName to create a type giving its fully-qualified name #68929

Closed
andig opened this issue Aug 18, 2024 · 4 comments
Closed
Labels
Milestone

Comments

@andig
Copy link
Contributor

andig commented Aug 18, 2024

Proposal Details

Consider adding a function to the reflect package for creating a type by it's name:

// `TypeByName` creates a Type given its name.
// It panics if the result type is not reachable.
func TypeByName(name string) Type

This can e.g. be useful with generated code where the go generate directive contains information about the required types. Having TypeByName allows the generate implementation to reason about the types without having to hard-code them.

Example:

typ := reflect.TypeByName("api.Meter")
val := reflect.New(typ)
for i := range val.NumMethod() {
    m := val.Method(i)
}

To work around

It panics if the result type is not reachable.

generate (or any other package using this function) would still need to (_) import the type's packages.

Note: this proposal is equivalent to the older #21754 but adds a use case.

@andig andig added the Proposal label Aug 18, 2024
@gopherbot gopherbot added this to the Proposal milestone Aug 18, 2024
@gabyhelp
Copy link

Related Issues and Documentation

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

@robpike
Copy link
Contributor

robpike commented Aug 18, 2024

Duplicate of closed #21754. The new use case does not address the dead code elimination problem of the first proposal.

@andig
Copy link
Contributor Author

andig commented Aug 18, 2024

This allows the linker to aggressively remove dead code, making binaries smaller. Otherwise, when you import a package, all of the code in that package would have to be included in the final binary, because the linker does not know what will be requested at run time.

I do feel that the panic adequately explains that linker can proceed as needed. This would only give access to the types that already are included. But maybe this is too clumsy or awkward?

@seankhliao
Copy link
Member

Duplicate of #21754

@seankhliao seankhliao marked this as a duplicate of #21754 Aug 19, 2024
@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Aug 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants