0
0
Goprogramming~5 mins

Package scope rules in Go

Choose your learning style9 modes available
Introduction
Package scope rules help decide where variables and functions can be used in Go programs. This keeps code organized and safe.
When you want to share a variable or function with all files in the same package.
When you want to hide details inside a package so other packages cannot access them.
When you want to organize code into reusable parts without exposing everything.
When you want to avoid name conflicts by limiting where names are visible.
Syntax
Go
package mypackage

var packageVar = 10 // visible inside the package

func packageFunc() {
    // function visible inside the package
}

func ExportedFunc() {
    // function visible outside the package because it starts with uppercase
}
Names starting with a lowercase letter are visible only inside the package.
Names starting with an uppercase letter are visible outside the package (exported).
Examples
Variable 'count' is visible to all functions in the package 'main'.
Go
package main

var count int = 5 // package scope variable

func increment() {
    count++ // accessible here
}

func main() {
    increment()
    println(count) // prints 6
}
Variable 'helperVar' is only visible inside 'utils' package because it starts with lowercase.
Go
package utils

var helperVar = 100 // package scope, not exported

func HelperFunc() int {
    return helperVar
}
Function 'ExportedFunc' starts with uppercase, so it can be used outside the 'utils' package.
Go
package utils

func ExportedFunc() string {
    return "Hello"
}
Sample Program
This program shows a variable with package scope used inside two functions in the same package.
Go
package main

import "fmt"

var packageVar = 42 // package scope variable

func printVar() {
    fmt.Println(packageVar) // accessible here
}

func main() {
    printVar() // prints 42
    // fmt.Println(packageVar) also works here because main is the same package
}
OutputSuccess
Important Notes
Package scope means the name is visible to all files in the same package.
Use uppercase first letter to export names outside the package.
Use lowercase first letter to keep names private to the package.
Summary
Package scope controls where variables and functions can be used inside a package.
Lowercase names are private to the package; uppercase names are public (exported).
This helps organize code and control access between packages.