3 ms·
My advice would be this: If you have a specific reusable component.. Make a package to contain it. Use init() to compile any regular expressions and store them
by dana321 8y ago
My advice would be this: If you have a specific reusable component.. Make a package to contain it.
Use init() to compile any regular expressions and store them as variables within that package, so that you don't
Split out related code in a folder, remembering that the included code is done in alphabetical order - so shared functions within the same package you should alphabetically make it the first to be included.
You can register components of a larger system by using the init() function to call a function in the base package, and within the calling package (usually main) import the "plugin" using the underscore space prefix (sql database drivers use this method)
Use the new go modules system; its great. But sometimes it doesn't include the latest packages, just modify the go.mod file and anything after the package name remove it and just put master instead.
One last thing with error handling. Everybody does if err!=nil. I tend to go the opposite way, if err==nil and nest these, if err isn't nil i drop out and deal with the error. If it is ok, it will return ok.
- deleted 8y ago[deleted]
- undreren 8y ago> One last thing with error handling. Everybody does if err!=nil. I tend to go the opposite way, if err==nil and nest these, if err isn't nil i drop out and deal with the error. If it is ok, it will return ok. Don't you get "staircase of doom"? err := unsafe1() if err == nil { err = unsafe2() if err == nil { err = unsafe3() if err == nil { err = unsafe4() if err == nil { err = unsafe5() if err == nil { // ... } } } } }
- jimsmart 8y ago> Use init() to compile any regular expressions and store them as variables within that package No need to resort to init() for regexps, simply use an unexported package level variable: var validFoo = regexp.MustCompile(...)