Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create constants visible across packages, accessible directly

Tags:

go

I would like to define my Error Codes in a package models.

error.go

package models

const{
  EOK = iota
  EFAILED
}

How can I use them in another package without referring to them as models.EOK. I would like to use directly as EOK, since these codes would be common across all packages.

Is it the right way to do it? Any better alternatives?

like image 315
lionelmessi Avatar asked Dec 19 '22 21:12

lionelmessi


1 Answers

To answer you core question

You can use the dot import syntax to import the exported symbols from another package directly into your package's namespace (godoc):

import . "models"

This way you could directly refer to the EOK constant without prefixing it with models.

However I'd strongly advice against doing so, as it generates rather unreadable code. see below

General/style advice

  1. Don't use unprefixed export path like models. This is considered bad style as it will easily globber. Even for small projects, that are used only internally, use something like myname/models. see goblog
  2. Regarding your question about error generation, there are functions for generating error values, e.g. errors.New (godoc) and fmt.Errorf (godoc). For a general introduction on go and error handling see goblog
like image 196
tike Avatar answered Feb 22 '23 23:02

tike