创建一片混凝土类型并将其铸造到各自的界面

时间:2016-09-01 18:40:44

标签: go

在创建一系列接口并将其启动到具体类型时遇到一些问题,任何帮助都会有很大的吸引力

接口

type MatrixElement interface {
    GetValue() Element
    GetCoordinate() Coordinate
}

具体实施

type LocatableElement struct {
    value datastructures.Element
    coordinate datastructures.Coordinate
}

func (ele LocatableElement)GetValue() datastructures.Element {
    return ele.value
}

func (ele LocatableElement)GetCoordinate() datastructures.Coordinate {
    return ele.coordinate
}

func CreateLocatableElement(value datastructures.Element, coordinate datastructures.Coordinate) LocatableElement {
    return LocatableElement{
        value: value,
        coordinate: coordinate,
    }
}

将类型定义为切片

type HorizontalMatrix [][]datastructures.MatrixElement

创建新Horizo​​natlMatrix的实例

func CreateHorizontalMatrix(rows int, columns int) HorizontalMatrix {
    horzMatrix := make([][]matrix.LocatableElement, rows)
    for i := 0; i < rows; i++ {
        horzMatrix[i] = make([]matrix.LocatableElement, columns)
    }
    return horzMatrix;
}

cannot use horzMatrix (type [][]matrix.LocatableElement) as type HorizontalMatrix in return argument

1 个答案:

答案 0 :(得分:1)

你既不能强制[]ConcreteTypes([]Interfaces)也不能宣称[]Interfaces.([]ConcreteTypes) ConcreteTypes实现Interfaces。您应该定义容器

type Matrix interface{
    GetElem(abs, ord int) MatrixElement 
}

并为HorizontalMatrix满足,或将矩阵设为[] interface

horzMatrix := make([][]matrix.MatrixElement, rows)
horzMatrix[i] = make([]matrix.MatrixElement, columns)

然后用具体类型LocatableElement

填充它