douwen3198 2019-03-09 22:45
浏览 92
已采纳

在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?

  • 写回答

2条回答 默认 最新

  • douyiavxxh02727 2019-03-09 23:01
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备