How to Retrieve Current and Specific User Info in Go and Convert IDs to Integers
This guide shows how to use Go's os/user package to obtain the current or a specified user's UID and GID, explains the effect of sudo on the reported user, and demonstrates converting those string IDs to int or int64 with strconv functions.
Reading font

In Go, the os/user package provides functions for accessing Linux user information such as user ID (UID) and group ID (GID). The following example obtains the current user and prints its UID and GID:
package main
import (
"fmt"
"os/user"
)
func main() {
// Get the current user
currentUser, err := user.Current()
if err != nil {
panic(err)
}
// Print UID and GID
fmt.Println("User ID:", currentUser.Uid)
fmt.Println("Group ID:", currentUser.Gid)
}The program calls user.Current() to retrieve the executing user's details; if an error occurs, it panics. Note that when the program is run with sudo, the reported user is root because sudo executes the command with super‑user privileges.
To fetch information for a particular username, use user.Lookup. The example below looks up a user named your_username and prints its UID and GID:
package main
import (
"fmt"
"os/user"
)
func main() {
// Specify the username
username := "your_username"
// Retrieve user information
userInfo, err := user.Lookup(username)
if err != nil {
panic(err)
}
// Print UID and GID
fmt.Println("User ID:", userInfo.Uid)
fmt.Println("Group ID:", userInfo.Gid)
}Both Uid and Gid are returned as strings. To work with them as numeric types, convert the strings using the strconv package. For an int conversion, use strconv.Atoi:
package main
import (
"fmt"
"strconv"
)
func main() {
// Convert numeric string to int
numStr := "123"
num, err := strconv.Atoi(numStr)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(num)
}
}For a 64‑bit integer, use strconv.ParseInt with base 10 and a 64‑bit size:
package main
import (
"fmt"
"strconv"
)
func main() {
// Convert numeric string to int64
numStr64 := "1234567890123456789"
num64, err := strconv.ParseInt(numStr64, 10, 64)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(num64)
}
}
These snippets demonstrate how to retrieve user identifiers and safely transform them into integer types for further processing in Go applications.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.