-2

Since Go uses an composition system instead of (multiple) inheritance, I'm just wondering about these 3 code snippets. Go says they force the programmer to use composition.

A) should be (almost) correct Go-Code, B) pseudo C) pseudo

Imho the result will always be the same on all three codes, beside the fact, that B) and C) can be used for even more stuff and A) forces you to stick to composition?

Even if you assume B) to not have the sort-method inside of the class but - lets say global like A) doesn't make a real difference oO

A) Go code:

interface Sort
    Len()
    Less(i, j int) bool
    Swap(i, j int)

func (qs *Sort) sort()
    doTheSorting

type MyData struct {
    var value int
}

func (s *MyData) Len() { ... }
func (s *MyData) Less(i, j int) bool { ... }
func (s *MyData) Swap(i, j int) { ... }

B) Looks like Inheritance but can imho be seen as embedded, according to how the compiler works.

class Sort

    public sort() { ... }

    abstract Len()
    abstract Less(i, j int) bool
    abstract Swap(i, j int)

C)

interface SortInterface
    void Len()
    bool Less(i, j int)
    void Swap(i, j int)

class Sort implements SortInterface
    public sort() { ... }

Usage B and C:

class MyClass **embed** Sort

    int value

    void Len() { ... }
    bool Less(i, j int) { ... }
    void Swap(i, j int) { ... }
4

1 に答える 1

4

いいえ、これはgoの仕組みではありません。ソート可能なタイプの例(標準ライブラリから取得)を次に示します。

type IntSlice []int

func (p IntSlice) Len() int           { return len(p) }
func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p IntSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

これにより、インターフェースが実装されます。

// Name of interface changed for clarity
type Sort interface {
    Len() int
    Less(i, j int) bool
    Swap(i, j int)
}

インターフェイスを実装するタイプSortは、新しいメソッドを取得しません。例のようなインターフェースにメソッドを割り当てることはできませんfunc (qs *Sort) sort() {...}

ただし、型の変数を期待する関数やメソッドに渡すことは許可されていますSort。このため、電話をかけることができ、sort.Sort(myIntSlice)並べ替えられます。

Sortこれは、インターフェースを実装するパラメーターを受け取る関数の例です。

func IsSorted(data Sort) bool {
    n := data.Len()
    for i := n - 1; i > 0; i-- {
        if data.Less(i, i-1) {
            return false
        }
    }
    return true
}

IsSorted、関数は実際のデータ型が何であるかを認識していません。それはIntSlice何か他のものである可能性があります。それが知っていることは、あなたがそれに与えたどんなパラメータも、Sortインターフェースのメソッドを実装するということです。

しかし、あなたが尋ねた質問を理解することができないようです。また、疑似コードは非常に理解しにくいものです。javaなどの別の言語を使用する方が良かったでしょう。

于 2012-06-22T00:25:20.803 に答える