duanci19881003 2018-09-18 19:06
浏览 13
已采纳

如何创建扩展类型

I see that it's possible to extend imported packages, for example to add new methods.

However, I try this to create a new instance of my own struct:

package main

import (
    "github.com/intdxdt/rtree"
)

type RTree struct {
    rtree.RTree
}

func NewRTree(nodeCap ...int) *RTree {
    return rtree.NewRTree(nodeCap...)
}

I saw similar example at other question. But I get an error: cannot use rtree.NewRTree(nodeCap...) (type *rtree.RTree) as type *RTree in return argument.

The question is - how do I init and use my own struct with my own methods and all imported methods/fields included?

  • 写回答

1条回答 默认 最新

  • dongzha5934 2018-09-18 19:37
    关注

    Always remember, Go doesn't support inheritance. It supports composition.

    You may call it inheritance, as far as it helps you to logically map between other OOP languages, and Go. Rule of thumb, whenever something doesn't work the way it works in OOP world, think in terms of composition.

    But when it comes to writing actual code, always remember that there is no is a relationship in composition, and it's always has a, even if it seems otherwise, because of the fact that you can actually access the member variables and methods of the composed/embedded(still, not inherited) struct. You can even override the method, if you declare the same with the new struct. Here's another catch - You still won't be able to access un-exposed (close to protected from Java-world) variables and functions of a struct in another package, as it seems in your case.

    But, your type RTree has rtree.RTree, but is never going to be a rtree.RTree, and will always be a different type for the compiler.

    package main
    
    import (
        "github.com/intdxdt/rtree"
    )
    
    type RTree struct {
        rtree.RTree
    }
    
    func NewRTree(nodeCap ...int) *RTree {
        return &RTree{
            RTree: *rtree.NewRTree(nodeCap...),
        }
    }
    

    On a separate node, unless you have more parameters to add, why not use rtree.RTree directly? Composing it, will give you all the methods of the enclosing type, but you can't pass it to any function that expects the enclosing type. Good news is, you will implicitly satisfy the interfaces that enclosing type satisfies, and hence you can pass it to functions that accept those interfaces.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 php 将rtmp协议转hls协议,无法播放
  • ¥15 miniconda安装不了
  • ¥20 python代码编写
  • ¥20 使用MPI广播数据遇到阻塞
  • ¥15 TinyMCE如何去掉自动弹出的“链接…”工具?
  • ¥15 微信支付转账凭证,如何解决
  • ¥15 在win10下使用指纹登录时,界面上的文字最后一个字产生换行现象
  • ¥20 使用AT89C51微控制器和MAX7219驱动器来实现0到99秒的秒表计数,有开始和暂停以及复位功能,下面有仿真图,请根据仿真图来设计c语言程序
  • ¥15 51单片机 双路ad同步采样
  • ¥15 使用xdocreport 生成word