Obtaining User Home Directory in Go
Querying a user's home directory is a common task in programming. In Go, accessing this information has evolved over different versions.
Recommended Approach
Since Go 1.12, the preferred method is to utilize the os.UserHomeDir function:
import ( "fmt" "log" "os" ) func main() { dirname, err := os.UserHomeDir() if err != nil { log.Fatal(err) } fmt.Println(dirname) }
Legacy Recommendation (Go 1.0.3)
Prior to Go 1.12, the recommended approach involved using the user.Current function from the os/user package:
import ( "fmt" "log" "os/user" ) func main() { usr, err := user.Current() if err != nil { log.Fatal(err) } fmt.Println(usr.HomeDir) }
Cross-Platform Compatibility
Both os.UserHomeDir and user.Current are documented to work on the following platforms:
The above is the detailed content of How Do I Get the User's Home Directory in Go?. For more information, please follow other related articles on the PHP Chinese website!