go version: 1.8
I've been playing with StructOf to build go values that match a serialized schema-driven form.
I've encountered an edge case that I'm uncertain whether Go currently supports. Given the struct:
type S struct {
Ptr *S
}
I see no way to forward-declare the S struct to use it as a pointer field to StructOf.
Is there some way I can build this struct type?
/cc @crawshaw
You can't do it. This is essentially a dup of #16522. Since you can't build a named type with reflect, you can't build a self-referential type.
@ianlancetaylor I don't see how this is essentially a dupe, though it is certainly related (and blocked on) #16522.
With #16522 you could do
s := reflect.StructOf(someFields) //want this to contain n but n doesn't exist yet
n := reflect.NamedOf(s, "S", nil)
but without a mechanism for forward declaration, as mentioned in the OP, how do you add a field to s of type n when the construction of n requires that s was already constructed?
(A related concern came up in #4146 where you would need n to define the signatures of the methods to add to n, but that's easier to handle).
s := reflect.StructOf(someFields) //want this to contain n but n doesn't exist yet
n := reflect.NamedOf(s, "S", nil)
If accepted and implemented, proposal https://github.com/golang/go/issues/39528 would solve this
Most helpful comment
s := reflect.StructOf(someFields) //want this to contain n but n doesn't exist yet
n := reflect.NamedOf(s, "S", nil)