-1

I've created a struct, that has the same shape, except the name of the struct:

type Response struct {
    code int
    body string
}


type Request struct {
  code int
  body string
}

The question is, does it exist a way to abstract the body of the struct?

For example:

type Response struct {
    Payload
}


type Request struct {
  Payload
}

type Payload struct {

    code int
    body string

}

When I create here a new struct, for example

a := Response{ Payload { code:200, body: "Hello world" } }

but I would like to omit to write Payload every time as:

a := Response{ code:200, body: "Hello world" }

Is it possible to embed a struct to another struct and to omit the name of the struct?

softshipper
  • 32,463
  • 51
  • 192
  • 400
  • 2
    If they're identical, why do you have two different structs? Perhaps a single struct called `Message` or `Payload`. – lurker Jan 01 '20 at 16:06
  • See also [How do I initialize a composed struct in Go?](https://stackoverflow.com/q/44123399/1256452) and (older, from different earlier compiler error message) [Embedding structs in golang gives error “unknown field”](https://stackoverflow.com/q/41686692/1256452). – torek Jan 01 '20 at 20:32

1 Answers1

3

I tried the following code in playground and it worked, maybe it's what you are looking for: https://play.golang.org/p/3c8lsNyV9_1

// You can edit this code!
// Click here and start typing.
package main

import "fmt"

type Response Payload


type Request Payload

type Payload struct {

    code int
    body string

}
func main() {
    a := Response{ code:200, body: "Hello response" }
    b := Request{ code:200, body: "Hello request" }
    fmt.Println(a)
    fmt.Println(b)
}
atakanyenel
  • 1,367
  • 1
  • 15
  • 20