I'm writing a go adapter for an c library. As my experience with go and c is limited I'm unsure how to handle int parameters because of the different size.

There are 2 approaches I thought of:

  1. Don't us the "int" type only use int32 like: func libcall(start,length int32) (int,error)

    • For me this feels like adding a lot unnecessary casting but it also explicitly tells the developer that your int shouldn't be greater than int32
  2. Take int parameters and check if the passed values aren't bigger than int32 else throw a panic like:

    func libcall(start,length int) (int,error){
        if start > math.MaxInt32 {
            panic(errors.New("value of start is greater than int32"))
        }
        if length > math.MaxInt32 {
            panic(errors.New("value of length is greater than int32"))
        }
     ....
    }
    
    • Omits a lot of casting
    • actually panics instead of setting the value to -1

This is going to be an adapter for a linear programming c library.

What approach would be the best? Any better Ideas?

Everything is much appreciated!

  • I don't know much about go but I would be explicit as you can be about type information in any go functions called by the C library. For interop that explicitness tends to help a lot. Of course the users who use your stuff from go don't have to be exposed to all those gory details. I'm sure you can hide them away before it reaches their hands. But when ABI/compatibility is a concern, then explicitness really helps a lot because any implicitness is like a tripping point of sorts. – Dragon Energy Dec 9 at 16:52
  • And I'm coming from the standpoint of being one who managed to survive porting 16-bit DOS legacy codebases to 32-bit, and then from 32-bit to 64-bit (although I grew a lot some gray hairs in between). The lack of explicitness of types and their sizes can be a real nightmare when it comes to porting and interop. So I would encourage being as explicit as you can in both C and Go when they interop/communicate with each other. – Dragon Energy Dec 9 at 16:54

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.