Skip to content

proposal: reflect: reflect.StructOf support for circular references #71191

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

Closed
Anthony-Dong opened this issue Jan 9, 2025 · 2 comments
Closed
Labels
Milestone

Comments

@Anthony-Dong
Copy link

Proposal Details

Currently, I'm facing an issue. I want to use reflect.StructOf to dynamically build a structure based on a DSL (Domain-Specific Language), but I found that it does not support circular references. I used an unsafe approach to handle this. May I ask if the official implementation supports this?

func UnsafeReplaceFieldType(_st reflect.Type, index int, _rst reflect.Type) {
	field := createStructField(_st, index, _rst)
	st := toStructType(_st)
	st.fields[index] = field
}

func createStructField(st reflect.Type, index int, _rst reflect.Type) structField {
	if _rst.Kind() != reflect.Struct {
		panic(`expected a struct type`)
	}
	fields := make([]reflect.StructField, st.NumField())
	for i := 0; i < st.NumField(); i++ {
		field := st.Field(i)
		if i != index {
			fields[i] = field
			continue
		}
		field.Type = reflect.New(_rst).Type()
		fields[i] = field
	}
	s := toStructType(reflect.StructOf(fields))
	return s.fields[index]
}

func toStructType(t reflect.Type) *structType {
	if t.Kind() != reflect.Struct {
		panic(`expected a struct type`)
	}
	s := (*rtype)(reflect.ValueOf(t).UnsafePointer())
	tt := (*structType)(unsafe.Pointer(s))
	return tt
}
@gopherbot gopherbot added this to the Proposal milestone Jan 9, 2025
@ianlancetaylor
Copy link
Contributor

Thanks. Closing as a dup of #39717.

@ianlancetaylor ianlancetaylor closed this as not planned Won't fix, can't repro, duplicate, stale Jan 9, 2025
@gabyhelp
Copy link

gabyhelp commented Jan 9, 2025

Related Issues

Related Code Changes

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

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

4 participants