drwpbrv668670 2018-02-15 11:39
浏览 21
已采纳

为不同的go结构创建构造函数

I have a struct which I initiate in some process like following, and this is working as expected.

This is specific runner

type TestRunner struct {
    path string
    name string
}

func NewRunner(p string, n string) *TestRunner {
    return &TestRunner{
        path: p,
        name: n,
    }
}

Now I want in the same package to create another runner so I do it like this e.g.

Also specific runner

type TestRunner2 struct {
    path string
    name string
}

func NewRunner(p string, n string) *TestRunner2 {
    return &TestRunner2{
        path: p,
        name: n,
    }
}

Now I get error that the func NewRunner is exist

I have another file (in the same package) which include the interface

This is generic implementation (different file in the same package)

type Runner interface {
    Run(path string) error         
    ChangePath(newPath string) 
}

So maybe the NewRunner should be there, where its recommended to put the new object ?

obviously I can create NewRunner1 and NewRunner2 method in the file but im not sure if it’s recommended

  • 写回答

2条回答 默认 最新

  • dongshi4773 2018-02-15 12:58
    关注

    First, you should name your runners according to their functionality, not by number. FastRunner and SlowRunner or LocalRunner vs RemoteRunner. You get the idea. Then you should create a construct for each one:

    func NewFastRunner( ... ) *FastRunner {
        return &FastRunner{ ... }
    }
    
    func NewSlowRunner( ... ) *SlowRunner {
        return &SlowRunner{ ... }
    }
    

    This is standard practice, and makes for very readable, unambiguous code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?