sugar/sugar.go

140 lines
2.8 KiB
Go

// Package sugar provides convenience functions for keeping code clean and less repetitive.
package sugar
import (
"fmt"
"os"
)
/*
* Literal Addressers
*/
// IntPtr takes an int literal and returns a pointer.
func IntPtr(v int) *int {
return &v
}
// Int8Ptr takes an int8 literal and returns a pointer.
func Int8Ptr(v int8) *int8 {
return &v
}
// Int16Ptr takes an int16 literal and returns a pointer.
func Int16Ptr(v int16) *int16 {
return &v
}
// Int32Ptr takes an int32 literal and returns a pointer.
func Int32Ptr(v int32) *int32 {
return &v
}
// RunePtr takes a rune literal and returns a pointer.
func RunePtr(v rune) *rune {
return &v
}
// Int64Ptr takes an int64 literal and returns a pointer.
func Int64Ptr(v int64) *int64 {
return &v
}
// UintPtr takes a uint literal and returns a pointer.
func UintPtr(v uint) *uint {
return &v
}
// Uint8 takes a uint8 literal and returns a pointer.
func Uint8Ptr(v uint8) *uint8 {
return &v
}
// BytePtr takes a byte literal and returns a pointer.
func BytePtr(v byte) *byte {
return &v
}
// Uint16Ptr takes a uint16 literal and returns a pointer.
func Uint16Ptr(v uint16) *uint16 {
return &v
}
// Uint32Ptr takes uint32 literal and returns a pointer.
func Uint32Ptr(v uint32) *uint32 {
return &v
}
// Uint64Ptr takes uint64 literal and returns a pointer.
func Uint64Ptr(v uint64) *uint64 {
return &v
}
// Float32Ptr takes float32 literal and returns a pointer.
func Float32Ptr(v float32) *float32 {
return &v
}
// Float64Ptr takes a float64 literal and returns a pointer.
func Float64Ptr(v float64) *float64 {
return &v
}
// Complex64Ptr takes a complex64 literal and returns a pointer.
func Complex64Ptr(v complex64) *complex64 {
return &v
}
// Complex128Ptr takes a complex128 literal and returns a pointer.
func Complex128Ptr(v complex128) *complex128 {
return &v
}
// StringPtr takes a string literal and returns a pointer.
func StringPtr(v string) *string {
return &v
}
// StrPtr is an alias of StringPtr.
func StrPtr(v string) *string {
return &v
}
// BoolPtr takes a bool literal and returns a pointer.
func BoolPtr(v bool) *bool {
return &v
}
/*
* Error Handling
*/
// Check takes an error and prints it if it is not nil; but will continue.
func Check(err error) {
if err != nil {
fmt.Printf("%+v", err)
}
}
// CheckLog takes an error and a format function for leveraging a custom printer like a logger.
func CheckLog(err error, fn func(format string, a ...interface{})) {
if err != nil {
fn("%+v", err)
}
}
// CheckPanic takes an error and will panic if it is not nil.
func CheckPanic(err error) {
if err != nil {
panic(err)
}
}
// CheckExit takes an error and will print it and exit with status 1 if it is not nil.
func CheckExit(err error) {
if err != nil {
fmt.Printf("%+v", err)
os.Exit(1)
}
}