如何定义带有属性的接口?



我有一个问题:是否有可能为线性空间设置界面?

让我提醒你,在线性空间L中有一个元素相加和一个元素乘以一个数字的运算。此外,还满足了两个属性:

a+b in L

2)ak在L,k——标量

我以以下形式展示了线性空间的接口:

type Point interface {
}
type LinSpace interface {
Sum(x, y Point)
Prod(x Point, k float64)
}

如何在接口定义中解释上述两个属性?

接口只能包含方法。

你可以这样做:

// Effective Go says: interface names should contain prefix -er 
type LinSpacer interface {
Sum() float64
Prod(k float64) float64
}

// Struct that implements interface
type LinSpaceImpl struct {
A float64
B float64
}

// Implementation of Sum() method
// Also, You don't need to pass A and B vars
// because they're already exist in LinSpaceImpl
func (l *LinSpaceImpl) Sum() float64 {
return l.A + l.B
}

// Implementation of Prod() method
// Unlike the Sum() method, here we need extra param - k
// So it has to be passed, or You can add it to
// LinSpaceImpl as another fields but it doesn't
// make any sense though
func (l *LinSpaceImpl) Prod(k float64) float64 {
return l.A * k
}

// Unnecessary "constructor" to optimize Your main function
// And clarify code
func NewLinSpace(a, b float64) LinSpacer {
// Since LinSpaceImpl correctly implements LinSpacer interface
// You can return instance of LinSpaceImpl as LinSpacer
return &LinSpaceImpl{
A: a,
B: b,
}
}

然后你可以在你的主(或其他)函数中这样做:

// Use any float values
ls := NewLinSpace(11.2, 24.7)

fmt.Println(ls.Sum())      // 35.9
fmt.Println(ls.Prod(30.2)) // 338.23999999999995

这是如何"OOP">

最新更新