在Go构造函数中返回值vs指针 [英] returning value vs pointer in Go constructor

查看:235
本文介绍了在Go构造函数中返回值vs指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  func NewGender(值字符串)性别{ 
返回Gender {strings.TrimSpace(value)}
}

func NewGender(值字符串)* Gender {
return& Gender {strings.TrimSpace(value )}
}


解决方案

问题是非常广泛的一个,它很大程度上取决于您的其他API。所以这里只是一些你可能需要考虑的事情,而不是一个特定的顺序:


  • 不必要的指针导致GC的工作量增加。您可能会通过返回一个指针(一个单词)而不是一个结构体(零到多个单词)来赢得一些时间,但其中一些时间可能会在以后被GC扫描所使用。


  • 指针也可以表示存在或不存在某个事物,但通常使用逗号 - 成语表达式或返回错误。

  • 说到错误,如果返回 nil 出错,错误被忽略的可能性会更小(因为nil指针解引用会导致恐慌)。如果你需要某种形式的追踪(例如,你可以使用某种形式的追踪,检查构造函数创建的所有实例的可能性),必须返回一个指针,以便检查器可以看到对该值的所有更改。


  • 如果类型的大部分方法都有指针接收器,或者API中的大多数函数接受指向类型的指针而不是值,则返回指针更符合人体工程学。


  • ul>

    When building a simple object in go, what's the difference between these alternatives?

    func NewGender(value string) Gender {
        return Gender{strings.TrimSpace(value)}
    }
    
    func NewGender(value string) *Gender {
        return &Gender{strings.TrimSpace(value)}
    }
    

    解决方案

    The question is a really broad one, and it depends heavily on the rest of your API. So here are just some things you might need to consider when choosing one over another (in no particular order):

    • Unnecessary pointers lead to more work for the GC. You might win some time by returning a pointer (one word) rather than a struct (zero to many words), but some of that time might later be consumed by the GC scan.

    • Pointers can also signal presence or absence of a thing, although it's generally better to use comma-ok idiom for that, or return an error.

    • Speaking of errors, if you return nil with an error, the chance that the error will be ignored is smaller (because nil pointer dereference will result in panic). Then again, I don't think people who ignore errors are something you should really take into account.

    • If you need some form of tracking (for example, a possibility to inspect all instances ever created by your constructor), you have to return a pointer, so that all changes to the value would be visible to the inspector.

    • If most of the type's methods have a pointer receiver, or most functions in the API accept pointers to the type rather than values, it's more ergonomic to return a pointer.

    这篇关于在Go构造函数中返回值vs指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆