gowrapper

Reassigning constants when creating wrapper library in Go


I want to create my own wrapper library from the already existing lib A. Library A has some functions and also some constants, example:

package lib


const(
   HeaderA = "headerA"
   HeaderB = "headerB"
)

func doWork(string header) {
   // some work
}

Now the question is: Do I have to reassign these constants in my own library?

package mylib
const (
    myHeaderA = lib.HeaderA
    myHeaderB = lib.HeaderB
)

What is the best practice in this case? It seems ok to reassign them in order to make the user unaware of lib A, but what if this library has a ton of constants?


Solution

  • There is no "package embedding", so constants from lib will not magically appear to be constants of mylib. If you want to provide those same constants in mylib, yes, you have to provide (copy) all those.

    but what if this library has a ton of constants ?

    Then on your mission to provide a wrapper for such a library that has a ton of constants, you also have to provide a ton of constants yourself (if the users of mylib do need all those constants).

    If you want to mimic the complete functionality of lib, that raises the question whether you really need this, and wouldn't it be simpler to just use lib instead of mylib.

    Note that you may create a utility that would generate a .go source file for mylib that would "copy" all exported constants of lib. Check out the go/parser package for a starting point.