首页 > 解决方案 > 有没有办法将 struct 嵌入到 struct 中?

问题描述

我创建了一个结构,它具有相同的形状,除了结构的名称:

type Response struct {
    code int
    body string
}


type Request struct {
  code int
  body string
}

问题是,它是否存在一种抽象结构体的方法?

例如:

type Response struct {
    Payload
}


type Request struct {
  Payload
}

type Payload struct {

    code int
    body string

}

例如,当我在这里创建一个新结构时

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

但我想省略Payload每次都写成:

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

是否可以将一个结构嵌入到另一个结构中并省略结构的名称?

标签: go

解决方案


我在操场上尝试了以下代码并且它有效,也许这就是您正在寻找的: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)
}

推荐阅读