Can unsafe.Sizeof be used with weak types / cgo

602 views
Skip to first unread message

Dave Cheney

unread,
Apr 5, 2012, 3:21:32 AM4/5/12
to golang-nuts
Consider the following program

% more t.go
package main

import (
"syscall"
"unsafe"
"fmt"
)

func main() {
fmt.Println(unsafe.Sizeof(syscall.Timeval))
}
% go run t.go
# command-line-arguments
./t.go:10: type syscall.Timeval is not an expression
./t.go:10: invalid expression unsafe.Sizeof(syscall.Timeval)

Is this a bug, or a limitation of cgo derived types ?

Cheers

Dave

Rob 'Commander' Pike

unread,
Apr 5, 2012, 3:32:28 AM4/5/12
to Dave Cheney, golang-nuts
The function unsafe.Sizeof takes an expression as argument, not a
type. You want something like unsafe.Sizeof(syscall.TimeVal{})

-rob

Dave Cheney

unread,
Apr 5, 2012, 3:35:00 AM4/5/12
to Rob 'Commander' Pike, golang-nuts
Thank you for the explanation, I was confusing it with the C sizeof,
and probably using that incorrectly to boot.

Cheers

Dave

Rob 'Commander' Pike

unread,
Apr 5, 2012, 10:05:33 AM4/5/12
to Dave Cheney, golang-nuts
To be pedantic, C sizeof doesn't operate on types either. The sizeof
operator applies to an expression or - this is the tricky bit - a type
cast.

thus
sizeof i
but also
sizeof(int)
but not
sizeof int

People think C sizeof is a function but it's an operator; the
expression sizeof(int) parses differently from the way most people
interpret it.

We're getting off topic.

-rob

Reply all
Reply to author
Forward
0 new messages