Variable Declaration
Description
TheDisableCache variable controls whether the home directory is cached after detection. By default, caching is enabled (DisableCache = false), which improves performance for applications that frequently call Dir().
When set to true, every call to Dir() will re-detect the home directory using OS-specific methods, which is slower but ensures you always get the current value.
Type
When
false (default), the home directory is cached after first detection. When true, caching is disabled and the home directory is re-detected on every call to Dir().When to Use
SetDisableCache = true when:
- Dynamic environments: The home directory might change during program execution (very rare)
- Testing scenarios: You need to test different home directory configurations without calling
Reset()between tests - Fresh detection required: You must ensure the most up-to-date value every time
Default Behavior (Caching Enabled)
By default,DisableCache is false, meaning:
- First call to
Dir()detects the home directory using OS-specific methods - The result is stored in an internal cache
- Subsequent calls to
Dir()return the cached value immediately - The cache can be cleared with
Reset()
Usage Examples
Disable Caching Globally
Testing Without Cache
Temporarily Enable Caching
Comparing Performance
Implementation Details
WhenDisableCache is false (default):
Dir()checks if a cached value exists before detection- If cached value exists, it’s returned immediately
- If no cache exists, detection runs and the result is cached
DisableCache is true:
Dir()skips the cache check entirely- Detection always runs using OS-specific methods
- Results are still stored in the cache but never read
Thread Safety
Access to the cache is protected by a read-write mutex (sync.RWMutex), making it safe to:
- Set
DisableCachefrom one goroutine - Call
Dir()from multiple goroutines concurrently
DisableCache while other goroutines are calling Dir() may result in inconsistent behavior. It’s best to set DisableCache once at program startup.
Comparison with Reset()
DisableCache and Reset() serve different purposes:
| Feature | DisableCache = true | Reset() |
|---|---|---|
| Effect | Disables caching permanently | Clears cache once |
| Next call | Always re-detects | Re-detects once, then caches |
| Use case | Testing, dynamic environments | One-time cache invalidation |
| Performance | Slower (always detects) | Fast after reset |