dongshuzhuo5659
dongshuzhuo5659
2018-02-17 01:52

Golang OOP信息隐藏练习

已采纳

What can I do with Go struct to hide information? Go struct member is visible to all. How to hide a member in a package?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dsgixl5195 dsgixl5195 3年前

    Go is not an Object oriented language. But it encapsulates things at the package level.

    According to GoLang specification;-

    An identifier may be exported to permit access to it from another package. An identifier is exported if both:

    1. the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
    2. the identifier is declared in the package block or it is a field name or method name.

    All other identifiers are not exported.

    If you don't wants to make your struct variables public do not export them. use lowercase to create variables in a struct type. Unexported struct fields are only accessible to same package.

    // unexported struct
    type person struct {
        name string // unexported fields can be used only in the same package
        age  int
    }
    

    Only package level granularity is allowed in Go. One can declare struct in different package which can be used in those files wherever it is required

    点赞 评论 复制链接分享

相关推荐