Why is syscall trap type uintptr?


As a golang newbie, I just started to learn how to invoke syscall in go. For now, I know golang provides Syscall in sys/unix:

func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr)

where trap is a value of type uintptr.

However, I found in many tutorials, and even in golang’s own lib source, the trap is set with a value of int simply, say, the sysnum here.

I know uintptr is a bit like normal int, but I believe they are not same. Why not set trap to something like uintptr(unsafe.Pointer(callNum))?

Those constants are untyped; They only have a type where they are used, so when they’re passed as the trap parameter, they are passed as uintptr. They can also have a default type, which would be int, so if you were to assign them to a variable, then you’d have to convert it:

const UntypedInteger = 123

func main() {
    doSomething(UntypedInteger) // works.
    i := UntypedInteger // Untyped integer becomes int
    // doSomething(i) // won't work
    doSomething(uintptr(i)) // works.

func doSomething(p uintptr) { }
1 Like

Using an int directly as the syscall trap value can work because Go allows implicit conversions from int to uintptr when calling Syscall, It simplifies the code and aligns with the convention of system calls using integer values for traps. Using uintptr(unsafe.Pointer(callNum)) would add unnecessary complexity in most cases. Stick with the more common and straightforward approach.

1 Like