在Golang中初始化新类(将Java转换为Golang)

时间:2019-03-09 22:45:13

标签: java go

我正在尝试将此java转换为golang,现在有此错误。我不知道为什么会出现这个错误。

这是Java代码:

     ArrayList<Cell> path; // path does not repeat first cell
    String name;
    static int count = 0;

    public Path() {
        this.path = new ArrayList<>();
        this.name = "P" + (++this.count);
    }

    public Path(Path op) {
        this.path = new ArrayList<>();
        this.name = op.name;
        path.addAll((op.path));
    }

这是我写的

    type Path struct {
    name  string
    count int
    path  []Cell
}

func NewPath() (p *Path) {
    p = new(Path)
    p.path = []Cell{}
    p.count = 0
    p.name = "P" + strconv.Itoa(1+p.count)
    return
}

func NewPath(op Path) (p *Path) {
    p = new(Path)
    p.path = []Cell{}
    p.count = 0
    p.name = op.name
    p.path = append(p.path, op.path)
    return
}

go系统说我在重新声明NewPath时出错,错误是:

prog.go:21:6: NewPath redeclared in this block

如何调试?

2 个答案:

答案 0 :(得分:1)

Golang不支持重载的方法名称。

您只需要调用(一种)不同的方法即可。

答案 1 :(得分:0)

此代码中有两个问题,但是第一个和您指出的一个问题是,NewPath函数在此处定义了两次,因此Go引发错误。 Go不支持方法重载,因此解决此问题的最简单方法是将第二个函数重命名为其他函数。

下一个错误将是cannot use op.path (type []Cell) as type Cell in append,该错误发生在第二个p.path = append(p.path, op.path)函数的NewPath行中。发生这种情况是因为您试图将op.path(类型[]Cell)放入p.path(类型[]Cell)中,所以由于op.path的类型不是{{1 }}不能附加到Cell上。请注意,p.path与串联不同,而是从第二个开始接收所有参数,并将它们放在第一个参数内。要解决此问题,您可以使用append运算符将op.path解压缩到append中。这将使...的每个元素成为op.path的单独参数,并将每个元素放置在append的内部。

这是代码的重构版本:

p.path
相关问题