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

I am trying to convert this java to golang and now I have this bug. I don't know why this bug is showing up.

here is the java code:

     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));
    }

Here is what i wrote

    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
}

The go system said I am wrong in term of redeclaring NewPath, with the error:

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

How can I debug it?

There are a couple of issues in this code, but the first, and the one you point out, is that the NewPath function is defined twice here and Go throws an error because of this. Go does not support method overloading, so the simplest way to solve this would be to rename your second function to something else.

The next error you'll get is cannot use op.path (type []Cell) as type Cell in append, which happens in the line p.path = append(p.path, op.path) in the second NewPath function. This happens because you are trying to place op.path (type []Cell) into p.path (type []Cell), so since op.path is not of type Cell it cannot be appended to p.path. Note that append is not the same as concatenate, instead it takes all arguments from the second onward and places them inside the first argument. To fix this you can unpack op.path into append using the ... operator. This will make each element of op.path an individual argument to append, and each will be placed inside of p.path.

Here is a refactored version of your code:

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

func NewPathFromOriginal(op Path) (p *Path) { // renamed
    p = new(Path)
    p.path = []Cell{}
    p.count = 0
    p.name = op.name
    p.path = append(p.path, op.path...) // note the '...'
    return
}

Golang doesn't support overloaded method names.

You simply have to call (one of) the methods something different.