Archive for June, 2013

Go uintptr from interface{}

June 28th, 2013 No comments

Some C functions accept more than one type of struct, so I wanted a Go wrapper able to pass a uintptr derived from an interface{}. Go’s reflect package makes this easy:

package main

import (

type USN_JOURNAL_DATA struct {
  UsnJournalID    int
  FirstUsn        uint32
  NextUsn         uint32
  LowestValidUsn  uint32
  MaxUsn          uint32
  MaximumSize     uint32
  AllocationDelta uint32

func doitA(ujd *USN_JOURNAL_DATA) (size uintptr, align int, p uintptr) {
  v := reflect.ValueOf(ujd)
  t := v.Elem().Type()
  size = t.Size()
  align = t.Align()
  p = v.Pointer()

func doitB(i interface{}) (size uintptr, align int, p uintptr) {
  v := reflect.ValueOf(i)
  t := v.Elem().Type()
  size = t.Size()
  align = t.Align()
  p = v.Pointer()

func main() {
  a := USN_JOURNAL_DATA{1, 2, 3, 4, 5, 6, 7}
  size, align, p := doitA(&a)
  fmt.Println(size, align, p)
  size, align, p = doitB(&a)
  fmt.Println(size, align, p)

Interestingly, as demonstrated above, the same implementation can be used for a func accepting either a struct pointer or an interface{}.

Go import

June 18th, 2013 No comments

Go is a wonderful language, able to build complex applications with very minimal configuration information. For many apps, only import statements are required.

However, there are a couple of special import cases worth knowing about:

import . “”

From “If a program imports a standard package using import . “path”, additional names defined in the imported package in future releases may conflict with other names defined in the program. We do not recommend the use of import . outside of tests, and using it may cause a program to fail to compile in future releases.”

import _ “”

From Andrew Gerrand (Google): “Prefixing an import
with an underscore causes the package to be imported for its
side-effects only. (that is, it’s init functions are executed and
global variables initialized)”

Categories: Development Tags: ,