创建一个具体类型的切片并转换到其各自的接口

在创建接口切片并将其启动为具体类型时遇到一些问题,任何帮助都会非常感激


界面


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

创建新 HorizonatlMatrix 的实例


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


ibeautiful
浏览 145回答 1
1回答

慕后森

尽管如此 ,您既不能强制转换[]ConcreteTypes([]Interfaces)也不能断言implements 。您应该定义容器[]Interfaces.([]ConcreteTypes)ConcreteTypesInterfacestype Matrix interface{&nbsp; &nbsp; GetElem(abs, ord int) MatrixElement&nbsp;}并满足它HorizontalMatrix或使矩阵作为[]接口horzMatrix := make([][]matrix.MatrixElement, rows)horzMatrix[i] = make([]matrix.MatrixElement, columns)然后用具体类型填充它LocatableElement
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go