【问题标题】:Initialize embedded struct in Go在 Go 中初始化嵌入式结构
【发布时间】:2013-07-25 16:18:49
【问题描述】:

我有以下struct,其中包含net/http.Request

type MyRequest struct {
    http.Request
    PathParams map[string]string
}

现在我想在下面的函数中初始化匿名内部结构http.Request

func New(origRequest *http.Request, pathParams map[string]string) *MyRequest {
    req := new(MyRequest)
    req.PathParams = pathParams
    return req
}

如何使用参数origRequest 初始化内部结构?

【问题讨论】:

标签: struct go


【解决方案1】:
req := new(MyRequest)
req.PathParams = pathParams
req.Request = origRequest

或者...

req := &MyRequest{
  PathParams: pathParams
  Request: origRequest
}

请参阅:http://golang.org/ref/spec#Struct_types,了解有关嵌入和字段命名方式的更多信息。

【讨论】:

  • 我收到编译器错误cannot use origRequest (type *http.Request) as type http.Request in assignment。我猜这是因为Request 不是命名字段。
  • 不,这是因为字段的类型与 origRequest 的类型不同。改用 *origRequest 问题就消失了。
  • 你是对的:用星号取消引用或在结构中使用引用会有所帮助。谢谢。
  • 关于字段如何命名:“不合格的类型名称作为字段名称。”所以http.Request 最终被称为Request
【解决方案2】:

怎么样:

func New(origRequest *http.Request, pathParams map[string]string) *MyRequest {
        return &MyRequest{*origRequest, pathParams}
}

它表明不是

New(foo, bar)

你可能更喜欢

&MyRequest{*foo, bar}

直接。

【讨论】:

  • 如果有一些你不想自己初始化的字段,例如,sync.Mutex 类型的文件呢?
  • 互斥锁的零值应该是一个现成的互斥锁,因此您只需将其作为嵌入值包含在内即可:var hits struct { sync.Mutex n int } hits.Lock() hits.n++ hits.Unlock()(来自10 things you probably didn't know about Go
【解决方案3】:

正如上面 Jeremy 所示,匿名字段的“名称”与字段的类型相同。因此,如果 x 的值是一个包含匿名 int 的结构,那么 x.int 将引用该字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-22
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2011-05-28
    相关资源
    最近更新 更多