user2671513
user2671513

Reputation:

Interface as arguments. How is it possible?

Interface as arguments. How is it possible?

https://github.com/skelterjohn/go.matrix/blob/go1/matrix.go

This package has this interface

type MatrixRO interface {
  Nil() bool
  Rows() int
  Cols() int
  NumElements() int
  GetSize() (int, int)
  Get(i, j int) float64

  Plus(MatrixRO) (Matrix, error)
  Minus(MatrixRO) (Matrix, error)
  Times(MatrixRO) (Matrix, error)

  Det() float64
  Trace() float64

  String() string

  DenseMatrix() *DenseMatrix
  SparseMatrix() *SparseMatrix
}

interface has only methods. Not data structure. Then how come Plus(MatrixRO) receives the interface as arguments? How is it possible to operate plus even if MatrixRO does not have any data in it?

This function also receives

  func String(A MatrixRO) string {

MatrixRO as an argument.

How it is possible? Is is because of the line

DenseMatrix() *DenseMatrix
SparseMatrix() *SparseMatrix

? If it needs to embed something, shouldn't it be like the following?

DenseMatrix
SparseMatrix

p.s. DenseMatrix and SparseMatrix structures are defined like this:

type DenseMatrix struct {
  matrix
  elements []float64
  step int
}

Upvotes: 1

Views: 117

Answers (1)

James Henstridge
James Henstridge

Reputation: 43949

An interface only consists of a collection of methods, so if you are handed an interface value you've got two options:

  1. Use only the methods exposed by the interface.
  2. Use a type assertion to convert it to a concrete type.

I don't have any familiarity with the code in question, but I suspect that implementers of this MatrixRO type may do a combination of the two.

If a particular MatrixRO implementation knows a fast way to implement Plus when the other operand is of the same type, it could use a type assertion to decide whether to invoke the fast path.

If it doesn't recognise the type of the other operand, the DenseMatrix or SparseMatrix methods provide a way to access the data needed to perform the operation.

Upvotes: 3

Related Questions