结构体套结构体指针--有什么黑魔法么

2020-07-23 16:56:18 +08:00
 hongyexiaoqing

在看 k8s 源代码时候,有这么一段代码,其中 Complete()方法, 看注释是可以填充没有设置的字段,填充字段需要这么套娃么.

CompletedConfig --》 指针 completedConfig --》 Config 指针

// Config is the main context object for the controller manager.
type Config struct {
	ComponentConfig kubectrlmgrconfig.KubeControllerManagerConfiguration

	SecureServing *apiserver.SecureServingInfo
	// LoopbackClientConfig is a config for a privileged loopback connection
	LoopbackClientConfig *restclient.Config

	// TODO: remove deprecated insecure serving
	InsecureServing *apiserver.DeprecatedInsecureServingInfo
	Authentication  apiserver.AuthenticationInfo
	Authorization   apiserver.AuthorizationInfo

	// the general kube client
	Client *clientset.Clientset

	// the client only used for leader election
	LeaderElectionClient *clientset.Clientset

	// the rest config for the master
	Kubeconfig *restclient.Config

	// the event sink
	EventRecorder record.EventRecorder
}

type completedConfig struct {
	*Config
}

// CompletedConfig same as Config, just to swap private object.
type CompletedConfig struct {
	// Embed a private pointer that cannot be instantiated outside of this package.
	*completedConfig
}

// Complete fills in any fields not set that are required to have valid data. It's mutating the receiver.
func (c *Config) Complete() *CompletedConfig {
	cc := completedConfig{c}

	apiserver.AuthorizeClientBearerToken(c.LoopbackClientConfig, &c.Authentication, &c.Authorization)

	return &CompletedConfig{&cc}
}

1796 次点击
所在节点    Go 编程语言
7 条回复
wangritian
2020-07-23 17:37:07 +08:00
其他包可以创建 Config 对象,设置属性,然后通过 Complete 方法补全,得到一个隐藏全部细节的 CompletedConfig,不会有机会再改动属性,看上去是这个目的
lance6716
2020-07-23 18:45:40 +08:00
注释不是写的很清楚吗
yangbonis
2020-07-23 20:13:59 +08:00
only write once
yangbonis
2020-07-23 20:25:09 +08:00
它这个 comment 不如写成,Only allow write once access.
raaaaaar
2020-07-23 20:39:51 +08:00
手机看代码真难受
hongyexiaoqing
2020-07-24 15:33:03 +08:00
@wangritian
恩,谢谢,注释写的模拟量可
hongyexiaoqing
2020-07-24 15:38:53 +08:00
如果原始的 Config 改变了,感觉防止不了 Config 被改

比如

```
a := &Config{}

b:=a.Complete()

如果 a 在某个地方被改了,b 不是也被改了

```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/692559

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX