What is type uintptr in Golang?

Variables contain data, and data can be of different data types, or types for short. Golang is a statically typed language; this means the compiler must know the types of all the variables, either because they were explicitly indicated or because the compiler can infer the type from the code context. A type defines the set of values and the set of operations that can take place on those values.

Type uintptr in Golang is an integer type that is large enough to contain the bit pattern of any pointer. In other words, uintptr is an integer representation of a memory address. Below is how you declare a variable of type uintptr:

var var_name uintptr

uintptr is generally used to perform indirect arithmetic operations on unsafe pointers for unsafe memory access. First, unsafe.Pointer is converted to uintptr, and then the arithmetic operation is performed on uintptr. Finally, it is converted back to unsafe.Pointer, which now points to the new memory address as a result of the operation.

uintptr is also used to store and print the pointer address value. Since the variable with the type uintptr does not reference anything as it’s a plain integer, the pointer corresponding to that object can be garbage collected.

Example

package main
import "fmt"
func main() {
var var1 uintptr = 0xc82000c290
fmt.Println("Value of var1:", var1)
fmt.Printf("Type of var1: %T", var1)
}

Explanation

The above code declares the variable var1 with type uintptr, which is assigned the memory address 0xc82000c290. If you run the code, you can observe that the value of var1 is displayed as an integer.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved