Open In App

Identifiers in Go Language

In programming languages, identifiers are used for identification purposes. In other words, identifiers are the user-defined names of the program components. In the Go language, an identifier can be a variable name, function name, constant, statement label, package name, or type. 

Example:



package main
import "fmt"

func main() {

 var name = "GeeksforGeeks"
  
}

There is a total of three identifiers available in the above example:

Rules for Defining Identifiers: There are certain valid rules for defining a valid Go identifier. These rules should be followed, otherwise, we will get a compile-time error.



Example:

// Valid identifiers:
_geeks23
geeks
gek23sd
Geeks
geeKs
geeks_geeks

// Invalid identifiers:
212geeks
if
default

Note:

For Constants:
true, false, iota, nil

For Types:
int, int8, int16, int32, int64, uint,
uint8, uint16, uint32, uint64, uintptr,
float32, float64, complex128, complex64,
bool, byte, rune, string, error

For Functions:
make, len, cap, new, append, copy, close, 
delete, complex, real, imag, panic, recover

In the below example, file1.go contains an exported variable called ExportedVariable, which is accessible within the same file. It also imports the file2 package and accesses the exported variable AnotherExportedVariable from file2.go. By running go run file1.go, it will print the value of ExportedVariable (“Hello, World!”) from file1.go and the value of AnotherExportedVariable (“Greetings from file2!”) from file2.go. This demonstrates the concept of exported identifiers being accessible from another package in Go.

Example of file2:




//file2.go
 
package file2
 
// Exported variable
var AnotherExportedVariable = "Greetings from file2!"

Example of file1:




// file1.go
 
package main
 
import (
    "fmt"
    "github.com/yourusername/project/file2"
)
 
// Exported variable
var ExportedVariable = "Hello, World!"
 
func main() {
    // Accessing exported identifier in the same file
    fmt.Println(ExportedVariable)
 
    // Accessing exported identifier from another package
    fmt.Println(file2.AnotherExportedVariable)
}

Output:

Hello, World!
Greetings from file2!

Article Tags :