go - 有没有办法将 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" }
是否可以将一个结构嵌入到另一个结构中并省略结构的名称?
解决方案
我在操场上尝试了以下代码并且它有效,也许这就是您正在寻找的: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)
}
推荐阅读
- mysql - 为什么 pandas read_sql_query 用问号替换 utf8 字符
- java - 3路/4路循环赛调度算法
- javascript - 使用 window.print() 时失去焦点
- c# - 如何使用图片框从一张图像中执行 2 状态按钮
- powershell - AAD Application Client Secret
- django - Django-ORM:为什么 distinct() 不能使用注释?
- polymer - Vaadin 缓存.js
- php - 在 .htaccess 中更改 PHP 版本后出现内部服务器错误
- spring-boot - 如何解决共享 Amazon S3 预签名 URL 的风险?
- php - php 文件在 localhost 服务器中工作,但不在 cpanel 中