【问题标题】:Is there a way to embed struct into struct?有没有办法将结构嵌入到结构中?
【发布时间】:2020-01-01 16:02:46
【问题描述】:

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

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


【解决方案1】:

我在操场上尝试了以下代码,它成功了,也许这就是你要找的: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)
}

【讨论】:

  • 似乎是一个非常合适的方法。
  • 还有什么,当我想添加一些特定于Response 的内容时,例如foo: string 字段?
  • 我不知道,也许是一个界面,或者就像你在问题正文中所做的那样。不过,这不是您的问题的一部分,其中指出:that has the same shape, except the name
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多