登录
首页 >  Golang >  Go问答

属性接口的定义方法

来源:stackoverflow

时间:2024-02-07 09:45:23 372浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《属性接口的定义方法》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我有一个问题:是否可以为线性空间设置接口?

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

1)l 中的 a+b

2)l 中的ak,其中 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”在 go 中的工作原理。

以上就是《属性接口的定义方法》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>