Go语言嵌入结构体类型转换报错:无法将*Req转换为TestReq的原因解析
Let's break down why your code is failing and how to fix it clearly:
1. Go's type system doesn't equate structurally similar types
Even though TestReq embeds Req and their underlying fields look identical, they are distinct, unrelated types in Go:
*Reqis a pointer to theReqstruct typeTestReqis a brand-new struct type that happens to includeReqas an embedded value field
Go is statically typed and enforces strict type compatibility. Two types are only convertible if they share the exact same underlying definition (e.g., two type aliases for the same struct) or if you explicitly define a conversion method. Embedding doesn't make types interchangeable—it just lets TestReq reuse Req's fields and methods.
2. Your conversion is invalid due to type mismatch
Your code attempts to convert a *Req pointer directly to TestReq (a value type), which Go rejects outright. These are fundamentally incompatible: one is a pointer to a struct, the other is a struct that contains a struct. There's no implicit conversion path between them.
3. How to correctly create a TestReq from a *Req
If you want to build a TestReq using your existing *Req pointer, you need to explicitly initialize the embedded Req field:
req := &Req{} // Dereference the pointer to get the Req value for the embedded field testReq := TestReq{*req}
If you intended TestReq to share state with Req (a common use case), you can embed a pointer instead:
// Redefine TestReq to embed a *Req pointer type TestReq struct { *Req } // Now you can assign the pointer directly req := &Req{} testReq := TestReq{req}
To recap: Embedding creates a "has-a" relationship (and enables method promotion), but it doesn't make types equivalent. You can't convert between unrelated types just because their fields overlap—you need to explicitly construct the target type using the source value or pointer.
内容的提问来源于stack exchange,提问作者papiro

