英文:
Interface as arguments. How is it possible?
问题
接口作为参数。这是怎么可能的?
这个包中有这个接口:
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
}
接口只有方法,没有数据结构。那么为什么 Plus(MatrixRO) 可以接收接口作为参数呢?
即使 MatrixRO 中没有任何数据,为什么还可以进行加法运算?
这个函数也接收了 func String(A MatrixRO) string
中的 MatrixRO 作为参数。
这是怎么可能的?是因为这一行吗?
DenseMatrix() *DenseMatrix
SparseMatrix() *SparseMatrix
如果需要嵌入某些东西,应该不是像下面这样吗?
DenseMatrix
SparseMatrix
附注:DenseMatrix 和 SparseMatrix 结构定义如下:
type DenseMatrix struct {
matrix
elements []float64
step int
}
英文:
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
}
答案1
得分: 3
一个接口只包含一组方法,所以如果你得到一个接口值,有两种选择:
- 只使用接口暴露的方法。
- 使用 类型断言 将其转换为具体类型。
我对相关代码不熟悉,但我猜测 MatrixRO
类型的实现者可能会结合这两种方法。
如果特定的 MatrixRO
实现知道在另一个操作数是相同类型时如何快速实现 Plus
,它可以使用类型断言来决定是否调用快速路径。
如果它无法识别另一个操作数的类型,DenseMatrix
或 SparseMatrix
方法提供了一种访问执行操作所需数据的方式。
英文:
An interface only consists of a collection of methods, so if you are handed an interface value you've got two options:
- Use only the methods exposed by the interface.
- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论