Google Go中抽象类/方法(Java)的等价性

Use*_*r42 12 java static-methods interface abstract go

我是Go的新手,我想知道如何在Java中实现类似于抽象类和方法的结构.在Java中,我会做以下事情:

abstract class A{

 static method1(){
  ...
  method2();
  ...
 }

 abstract method2();

}

class B extends A{

 method2(){
  ...
 }

}

class C extends A{

 method2(){
  ...
 }

}
Run Code Online (Sandbox Code Playgroud)

我知道接口和结构.我可以构建一个接口,然后构建一个struct来实现method1.但是方法2怎么样?我知道我可以在另一个接口中嵌入一个接口,并将结构作为另一个结构的字段嵌入.但我没有看到用这些方法实现我的结构的方法.

我看到的唯一解决方案是在B类和C类中实现method1.还有其他方法吗?

注意:当然,在我的情况下,它不仅仅是一种方法.此外,我有一个抽象类的层次结构,并不真的想把所有内容都移到'子类'.

我在互联网上找到的例子主要是每个界面只有一种方法.如果你们其中一个人能给我一个提示,那就太棒了!谢谢.

One*_*One 10

您可以拥有复合接口,例如来自io包:

http://golang.org/src/pkg/io/io.go?s=2987:3047#L57

type Reader interface {
    Read(p []byte) (n int, err error)
}
type Writer interface {
    Write(p []byte) (n int, err error)
}

type ReadWriter interface {
    Reader
    Writer
}
Run Code Online (Sandbox Code Playgroud)

作为旁注,不要尝试使用go实现java代码,尝试学习Go Way.


ANi*_*sus 7

由于Go没有staticOOP意义上的方法,因此您经常会看到这些类型的方法被实现为包级别函数:

package mypackage

func() Method1() { ... } // Below I will call it Function instead
Run Code Online (Sandbox Code Playgroud)

然后,这样的包级别函数将接口作为参数.在这种情况下,您的代码看起来像这样:

package main

import "fmt"

type Methoder interface {
    Method()
}

func Function(m Methoder) {
    m.Method()
}

type StructB struct{}

func (s *StructB) Method() { fmt.Println("StructB") }

type StructC struct{} // You can do some "inheritance" by embedding a base struct

func (s *StructC) Method() { fmt.Println("StructC") }

func main() {    
    b := &StructB{}
    Function(b)    
}
Run Code Online (Sandbox Code Playgroud)

输出:

StructB
Run Code Online (Sandbox Code Playgroud)