35

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ですか?

4

3 に答える 3

35
req := new(MyRequest)
req.PathParams = pathParams
req.Request = origRequest

また...

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

埋め込みとフィールドの命名方法の詳細については、 http : //golang.org/ref/spec#Struct_typesを参照してください。

于 2012-09-21T20:15:13.670 に答える
19

どうですか:

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

代わりに

New(foo, bar)

あなたはただ好むかもしれません

&MyRequest{*foo, bar}

直接。

于 2012-09-21T20:38:52.093 に答える
7

Jeremy が上で示したように、無名フィールドの「名前」はフィールドの型と同じです。したがって、x の値が匿名の int を含む構造体である場合、x.int はそのフィールドを参照します。

于 2012-09-21T21:28:01.747 に答える