Skip to content

Conversation

cuiweixie
Copy link
Contributor

@cuiweixie cuiweixie commented Aug 27, 2025

Proposed changes

why you might use reflect.TypeFor instead of reflect.TypeOf in Go.


Background

In Go, the reflect package provides two similar-looking functions:

  • reflect.TypeOf(x)
    Takes a value x and returns its reflect.Type.
    Example:

    t := reflect.TypeOf(123) // type: int
  • reflect.TypeFor[T]() (introduced in Go 1.22)
    A generic function that returns the reflect.Type for a type parameter T without needing a value.
    Example:

    t := reflect.TypeFor[int]() // type: int

Why use reflect.TypeFor instead of reflect.TypeOf?

  1. No value needed

    • reflect.TypeOf requires an actual value at runtime.
      If you only know the type (not a value), you have to create a dummy value:
      t := reflect.TypeOf((*MyStruct)(nil)).Elem()
    • reflect.TypeFor works directly with the type parameter:
      t := reflect.TypeFor[MyStruct]()
      This is cleaner and avoids allocating or creating dummy values.
  2. Compile-time type safety

    • With reflect.TypeOf, the type is determined from a runtime value, so mistakes may only show up at runtime.
    • With reflect.TypeFor, the type is determined at compile time from the generic type parameter, so it’s safer and clearer.
  3. Better for generic code

    • In generic functions, you often have a type parameter T but no value of type T.
      reflect.TypeOf can’t be used without creating a zero value:
      func PrintType[T any]() {
          var zero T
          fmt.Println(reflect.TypeOf(zero))
      }
      With reflect.TypeFor, you can simply do:
      func PrintType[T any]() {
          fmt.Println(reflect.TypeFor[T]())
      }
  4. Avoids unnecessary allocations

    • Creating a dummy value for reflect.TypeOf may allocate memory (especially for composite types).
    • reflect.TypeFor avoids this overhead entirely.

Summary Table

Feature reflect.TypeOf reflect.TypeFor (Go 1.22+)
Requires a value ✅ Yes ❌ No
Works without allocation ❌ Sometimes allocates ✅ Yes
Compile-time type safety ❌ Runtime only ✅ Compile-time
Good for generics ❌ Needs zero value ✅ Directly works

Recommendation:
Use reflect.TypeFor when:

  • You know the type at compile time (especially in generic code).
  • You don’t have or don’t want to create a value.
  • You want cleaner, safer, and allocation-free code.

Use reflect.TypeOf when:

  • You already have a value and want its type at runtime.

Checklist

  • Pull request is created against the dev branch
  • All checks passed (lint, unit/integration/regression tests etc.) with my changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Summary by CodeRabbit

  • Refactor
    • Streamlined internal handling of context-aware function wrapping to use a unified type lookup, improving consistency across modules.
    • No changes to public APIs, configuration, or usage.
    • Behavior remains unchanged; functions continue to receive context as before where applicable.
    • No performance impact expected.
    • This update is internal-only with no user-visible differences.

@auto-assign auto-assign bot requested a review from dogancanbakir August 27, 2025 09:03
Copy link
Contributor

coderabbitai bot commented Aug 27, 2025

Walkthrough

Replaced reflect.TypeOf((*context.Context)(nil)).Elem() with reflect.TypeForcontext.Context for first-parameter type checks in two wrappers, preserving existing behavior for context-aware function wrapping. No exported API changes or control-flow modifications.

Changes

Cohort / File(s) Summary
Context type acquisition refactor
pkg/js/gojs/gojs.go, pkg/js/gojs/set.go
Switched context type detection to reflect.TypeFor[context.Context]() in wrappers that conditionally inject context.Context based on the first parameter type; all other logic unchanged.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I twitch my whiskers at subtle delight,
A tiny refactor, clean as moonlight.
From Of to For, the types align,
Context arrives right on time.
In burrows of code, I hop and cheer—
Small hops today, smooth runs all year. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
pkg/js/gojs/set.go (2)

37-39: DRY the first-arg type check across wrappers.

Both wrappers duplicate the same guard. Consider a small helper for readability and consistency.

Apply within this hunk:

-	if fnType.NumIn() == 0 || fnType.In(0) != reflect.TypeFor[context.Context]() {
+	if !firstArgIsContext(fnType) {
 		return fn // Return original function unchanged if it doesn't have context.Context as first arg
 	}

Add once in the package (new file, e.g., pkg/js/gojs/reflectutil.go):

package gojs

import (
	"context"
	"reflect"
)

var ctxType = reflect.TypeFor[context.Context]()

func firstArgIsContext(t reflect.Type) bool {
	return t.NumIn() > 0 && t.In(0) == ctxType
}

89-92: Wrapper currently not used in RegisterFuncWithSignature.

wrapWithContext is commented out; this change won’t affect runtime behavior here. Intentional?

I can wire it up and add a focused test if desired.

pkg/js/gojs/gojs.go (1)

62-64: Apply shared helper to avoid duplication (optional).

Keep the check identical but centralize it.

Apply within this hunk:

-	if fnType.NumIn() == 0 || fnType.In(0) != reflect.TypeFor[context.Context]() {
+	if !firstArgIsContext(fnType) {
 		return fn // Return original function unchanged if it doesn't have context.Context as first arg
 	}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 8194fab and 52fc18e.

📒 Files selected for processing (2)
  • pkg/js/gojs/gojs.go (1 hunks)
  • pkg/js/gojs/set.go (1 hunks)
🔇 Additional comments (3)
pkg/js/gojs/set.go (2)

37-39: Good switch to reflect.TypeFor: semantics preserved, clearer intent.

Using reflect.TypeForcontext.Context removes the dummy value dance and keeps the exact-type check unchanged.


37-39: Go ≥1.22 Requirement Confirmed in go.mod – Please Verify CI Configuration

The project’s go.mod specifies go 1.24.1, which exceeds the Go 1.22 minimum needed for reflect.TypeForinvoke
However, I didn’t locate any GitHub Actions workflows under .github/workflows; please ensure your CI pipeline is configured to use Go 1.22 or higher (ideally matching 1.24+)—for example, by updating actions/setup-go in your workflow files.

Key locations using reflect.TypeFor:

  • pkg/js/gojs/gojs.go:62
  • pkg/js/gojs/set.go:37
pkg/js/gojs/gojs.go (1)

62-64: Consistent migration to reflect.TypeFor.

Matches set.go; behavior remains “exactly context.Context as first param or bail.”

@Mzack9999 Mzack9999 self-requested a review August 27, 2025 16:39
@ehsandeep ehsandeep merged commit d76187f into projectdiscovery:dev Aug 27, 2025
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants