我必须遵循代码:
包分析器
import (
"context"
"os"
"path/filepath"
"k8s.io/api/apps/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
"k8s.io/client-go/tools/clientcmd"
)
func getClientSetFromConfig() (*kubernetes.Clientset, error) {
kubeconfig := filepath.Join(os.Getenv("HOME"), ".kube/config")
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
panic(err)
}
return kubernetes.NewForConfig(config)
}
func GetDeploys() []v1beta1.Deployment {
clientset, err := getClientSetFromConfig()
if err != nil {
panic(err)
}
deploys, err := clientset.ExtensionsV1beta1().Deployments("").List(context.Background(), metav1.ListOptions{})
if err != nil {
panic(err)
}
return deploys.Items
}
我收到以下错误:
cannot use deploys.Items (variable of type []v1beta1.Deployment) as []v1beta1.Deployment value in return statement
这似乎没有意义。我试图改为v1beta1.DeploymentList
直接返回,但我得到了同样的错误。我以前在 Golang 中从未遇到过这种情况。
这种模式似乎是故意的k8s.io/client-go
。
- 这背后的理由是什么?
- 编写这样的函数的惯用方式是什么?
- golang 的哪些功能/模式允许人们编写这样的函数,其他人可以调用和检查返回的对象但不能进一步返回它们?
另外,附上go.mod
文件以供参考
module upgrades
go 1.14
require (
github.com/fsnotify/fsnotify v1.4.9 // indirect
github.com/imdario/mergo v0.3.9 // indirect
github.com/mitchellh/go-homedir v1.1.0
github.com/mitchellh/mapstructure v1.3.2 // indirect
github.com/pelletier/go-toml v1.8.0 // indirect
github.com/spf13/afero v1.2.2 // indirect
github.com/spf13/cast v1.3.1 // indirect
github.com/spf13/cobra v1.0.0
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.7.0
github.com/tealeg/xlsx v1.0.5
golang.org/x/sys v0.0.0-20200610111108-226ff32320da // indirect
gopkg.in/ini.v1 v1.57.0 // indirect
k8s.io/api v0.18.3
k8s.io/apimachinery v0.18.3
k8s.io/client-go v0.18.3
k8s.io/utils v0.0.0-20200603063816-c1c6865ac451 // indirect
)