Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize embedded struct in Go

Tags:

struct

go

I have the following struct which contains a net/http.Request:

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

Now I want to initialize the anonymous inner struct http.Request in the following function:

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

How can I initialize the inner struct with the parameter origRequest?

like image 689
deamon Avatar asked Sep 21 '12 20:09

deamon


1 Answers

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

or...

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

See: http://golang.org/ref/spec#Struct_types for more about embedding and how the fields get named.

like image 54
Jeremy Wall Avatar answered Oct 03 '22 01:10

Jeremy Wall