Golang Visibility Rules (public and private, access rights)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The go language does not have public, protected, private, and other access control modifiers like other languages, which control visibility by letter capitalization, if defined constants, variables, types, interfaces, structures, The name of a function, such as the beginning of a capital letter, means that it can be accessed or invoked by another package (equivalent to public), and the non-uppercase start can only be used within the package (the equivalent of private, variable or constant can also start with an underscore)

For example:

Visibility/test.go
Package Visibility Import "FMT" const PI = 3.145const Pi = 3.14const _pi = 3.14 var p int = 1var p int = 1 Func private_fu Nction ()  {fmt. Println ("Only used in this package!")} Func public_fuction () {fmt. Println ("used in Anywhere!")}

Main.go
Package main import ("Visibility" "FMT") func main () {visibility. Public_fuction ()//used in anywhere!//visibility.private_function ()//cannot access private functions and cannot be compiled by FMT. Println (visibility. P)//1//fmt. PRINTLN (VISIBILITY.P)//cannot access private variables and cannot be compiled by FMT. Println (visibility. PI)//3.14//fmt. PRINTLN (VISIBILITY.PI)//Cannot access private constants and cannot compile//fmt. PRINTLN (VISIBILITY._PI)//Cannot access private constants, cannot be compiled}

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.