登录
首页 >  Golang >  Go问答

空结构上定义方法接收器的做法是否不佳?

来源:stackoverflow

时间:2024-02-27 22:33:21 448浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《空结构上定义方法接收器的做法是否不佳?》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我看到一些代码在空结构上包含方法接收器。这是 go 中不好的编码习惯吗?

type example struct {
    // no attribute
}

func (e *example) dosomething() error {
    return nil
}

我应该推荐他使用 go 函数来代替吗?但是有什么理由呢?

func DoSomething() error {
    return nil
}

正确答案


这可能是有道理的,例如如果您想实现一个接口,您需要一个类型来完成它。在这种情况下,可能需要一个空结构。

type SomethingDoer interface {
    DoSomething() error
}

// Example implements the SomethingDoer interface.
type Example struct {
    // no attribute
}

func (e *Example) DoSomething() error {
    return nil
}

// A line like the following is sometimes used to assert
// that a type implements a specific interface.
var _ SomethingDoer = &Example{}

此外,正如 @notx 所提到的,有时您正在构建一个更大的东西,您可能会立即将其设为一种类型,因为您知道接下来要为其添加状态。我个人远离这种“防御性编程”,只在需要时添加类型。但风格和观点各有不同,因此这种情况并不少见。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

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