*golangs* 是什么意思?请提供更多上下文信息。

huangapple go评论69阅读模式
英文:

What is the common type to golangs *ecr.ECR and *ecs.ECS?

问题

我想编写一个 Golang 函数,根据输入返回相应的服务:

func GetService(service string) <在这里写什么> {
    session, _ := session.NewSession(&aws.Config{Region: aws.String(Region)})
    switch {
       case service == 'ecr':
	    var svc *ecr.ECR
        svc = ecr.New(session)
        return svc
       case service == 'ecs':
        var svc *ecs.ECS
        svc = ecs.New(session)
        return svc
   }
}

这类似于 AWS 服务的工厂函数,但是它们应该返回什么类型的公共类型呢?

英文:

I want to write a golang function which return the service according to the input:

func GetService(service string) &lt;what to write here&gt; {
    session, _ := session.NewSession(&amp;aws.Config{Region: aws.String(Region)})
    switch {
       case service == &#39;ecr&#39;:
	    var svc *ecr.ECR
        svc = ecr.New(session)
        return svc
       case service == &#39;ecs&#39;:
        var svc *ecs.ECS
        svc = ecs.New(session)
        return svc
   }
}

It is kind of factory for aws services, but what is their common type which has to be returned?

答案1

得分: 1

你可以编写两个函数,每个函数返回其中一个选项。

另一种选择是返回一个接口,让用户根据自己的了解将值转换为相应类型。如果对象具有相同名称的方法,接口还可以定义一些方法。

我认为最适合的方法是模块化方法,我将用伪代码进行演示。

func NewSession
    session, err = (创建会话)
    (处理错误)
    return session

// 现在让我们使用它
func MyUseCase
    ecr = NewEcr(NewSession())
    (使用 ecr)

你在代码中所抽象的东西实际上不需要抽象化。用户应该按照原样创建实例,因为这比进行类型转换更简单且更快。

抽象化的主要目标是简化顶层代码并消除重复。请记住这一点。

英文:

What you can do is write two functions where each will return either of these.

Other option is to return an interface and let the user cast the value as he knows what it is. Optionally interface can have some methods defined if object share methods with same name.

Last approach that I see is most fitting is a modular approach that I will also demonstrate. But with pseudo code.

func NewSession
    session, err = (create session)
    (handle error)
    return session

// now lets use this
func MyUseCase
    ecr = NewEcr(NewSession())
    (use ecr)

The thing you are abstracting in your code should not be abstracted at all. User should create his instance as it is simpler then casting it and even faster.

The main goal of abstraction is simplify top level code and eliminate repetition. Keep that in mind.

huangapple
  • 本文由 发表于 2021年7月16日 13:17:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/68403778.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定