-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?

2

1 Answer 1

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)
}
Sign up to request clarification or add additional context in comments.

3 Comments

Seems like a very suitable approach.
And what, when I want so add something specific to Response for example foo: string field?
I don't know, maybe an interface, or like how you did in your question body. Nevertheless that's not part of your question which states: that has the same shape, except the name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.