Exported names in Golang

Exported names in Go refer to identifiers (variables, functions, types, etc.) that are capitalized. These names are accessible outside the package where they are defined.

  1. Exported Variables:
   package example

   // Exported variable
   var ExportedVariable int = 10

   // Non-exported variable
   var nonExportedVariable int = 5

ExportedVariable is accessible from other packages because it starts with a capital letter, while nonExportedVariable is not.

  1. Exported Functions:
   package example

   // Exported function
   func ExportedFunction() {
       // Function body
   }

   // Non-exported function
   func nonExportedFunction() {
       // Function body
   }

ExportedFunction is accessible from other packages, but nonExportedFunction is not.

  1. Exported Types:
   package example

   // Exported type
   type ExportedStruct struct {
       // Struct fields
       Field1 int
       Field2 string
   }

   // Non-exported type
   type nonExportedStruct struct {
       // Struct fields
       Field1 int
       Field2 string
   }

ExportedStruct can be used in other packages, but nonExportedStruct cannot.

  1. Exported Constants:
   package example

   // Exported constant
   const ExportedConstant int = 100

   // Non-exported constant
   const nonExportedConstant int = 50

ExportedConstant can be accessed from other packages, while nonExportedConstant cannot.

They allow for encapsulation and control over what functionality is exposed to other parts of the program.

Leave a Comment