notnull

package
v1.0.0-beta.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 17 Imported by: 5 modules, 5 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

notnull

Never-null counterparts of some nullable types for NOT NULL columns and JSON fields that must not be null. The zero value of every type is written as a value: a nil array as the empty SQL array '{}' and JSON [], a nil JSON as the empty object {}, and TrimmedString as a possibly empty string. Use it when a column is NOT NULL DEFAULT '{}' and the Go code should not need nil checks.

import "github.com/domonda/go-types/notnull"

Why a nil slice maps to an empty array

nil is the zero value of a Go slice, what a slice variable or struct field holds before anything is assigned to it. Because this package models values that are NOT NULL, that default must not become SQL NULL or JSON null. The arrays treat it as the empty array instead:

  • Value and MarshalJSON write a nil or empty slice as '{}' and [], never as NULL or null.
  • Scan and UnmarshalJSON never produce a nil slice: SQL NULL, '{}', JSON null and [] all read as a non-nil empty slice.

To keep NULL apart from the empty array, use the nullable arrays instead.

Arrays

Type Element Methods besides Value, Scan, MarshalJSON and UnmarshalJSON
StringArray string Contains, Len, Less, Swap
IntArray int64 Contains, String, Len, Less, Swap
FloatArray float64 Contains, String, Len, Less, Swap
NullBoolArray sql.NullBool Bools (NULL elements as false), String
Method Description
Contains(value) Whether value is an element.
Len(), Less(i, j), Swap(i, j) sort.Interface in ascending element order.
String() [1, 2] for IntArray and FloatArray, [true, NULL] for NullBoolArray. A nil array prints []. StringArray has no String method.
Bools() []bool with NULL elements as false. Returns nil for an empty array.
Value() PostgreSQL array literal: {"a","b"} with quoted and escaped elements for StringArray, {1,2}, {1.5,2}, {t,f,NULL}. nil and empty write {}.
Scan(src) Parses a PostgreSQL array literal from a string or []byte. nil and {} read as an empty slice.
MarshalJSON() JSON array, [] for nil and empty. NULL elements of NullBoolArray as null. A NaN or ±Inf element of FloatArray returns a *json.UnsupportedValueError, like encoding/json for a float64.
UnmarshalJSON(data) JSON array, null reads as an empty slice. null elements of NullBoolArray read as NULL.

Every array implements driver.Valuer, sql.Scanner, json.Marshaler and json.Unmarshaler. IntArray, FloatArray and NullBoolArray also implement fmt.Stringer.

Value and Scan use the PostgreSQL array text format, which PostgreSQL, CockroachDB and YugabyteDB understand. Databases without array types, like MySQL, MariaDB, SQLite, SQL Server and Oracle, are not supported.

Array helpers

Function Description
SplitArray(array) Splits an SQL or JSON array literal into its top level elements and leaves quoted elements quoted. {}, [], null and NULL return a non-nil empty slice. An unquoted SQL NULL element is returned as NULL. A trailing comma yields an empty last element.
SplitArrayValues(array) Like SplitArray, but returns the value of quoted elements with quotes and escapes removed. Every SQL element is unescaped, in a JSON array only quoted strings are.
SQLArrayLiteral(strs) Joins strs as a quoted PostgreSQL array literal like {"a","b"}. nil and an empty slice return {}.

TrimmedString

type TrimmedString string trims every value with strutil.TrimSpace, which removes Unicode whitespace, non-printable runes like the BOM and zero-width characters, and invalid UTF-8 bytes. Unlike nullable.TrimmedString it has no null state: the empty string is a value and is written as '' and "".

Function or method Description
TrimmedStringFrom(str) Trimmed str.
TrimmedStringf(format, a...) Trimmed fmt.Sprintf result.
TrimmedStringJoin(sep, strs...) Trims every string of any ~string type and joins all of them with sep, empty ones included.
String() The trimmed string.
IsEmpty() Whether the trimmed string is empty.
Set(str) Assigns the trimmed str.
ToUpper(), ToLower() Case mapping of the trimmed string.
ToValidUTF8(replacement) Replaces invalid UTF-8 and trims the result.
Contains(substr), ContainsAny(chars), ContainsRune(r) strings functions on the trimmed string.
HasPrefix(prefix), HasSuffix(suffix) strings functions on the trimmed string.
TrimPrefix(prefix), TrimSuffix(suffix), ReplaceAll(old, new) strings functions, the result trimmed again.
Split(sep) strings.Split of the trimmed string with every part trimmed.

Implements: fmt.Stringer, driver.Valuer, sql.Scanner, encoding.TextMarshaler, encoding.TextUnmarshaler, json.Marshaler, json.Unmarshaler, xml.Marshaler, xml.Unmarshaler, xml.MarshalerAttr (pointer). It has no JSONSchema method.

JSON

type JSON []byte holds raw JSON text. A nil or empty JSON stands for the empty object {}.

Function or method Description
MarshalJSON(source) json.Marshal(source) as JSON.
MarshalFrom(source) Marshals source into the receiver. A nil source stores null.
UnmarshalTo(dest) json.Unmarshal into dest. A nil or empty JSON unmarshals {}.
IsEmpty() True for nil, "", {} and [].
Valid() json.Valid, but true for nil and empty.
String() The text, or {} for nil and empty.
GoString() notnull.JSON(`...`).
PrettyPrint(w) The text in backticks, {} for nil and empty, for github.com/domonda/go-pretty.
Clone() Copy. nil stays nil.

Implements: driver.Valuer, sql.Scanner, json.Marshaler, json.Unmarshaler, fmt.Stringer, fmt.GoStringer.

Serialization

Go value SQL Value() JSON Text
StringArray(nil), StringArray{} '{}' [] no text methods
StringArray{"a", "b c"} '{"a","b c"}' ["a","b c"] no text methods
IntArray(nil), IntArray{} '{}' [] no text methods
IntArray{1, 2} '{1,2}' [1,2] no text methods
NullBoolArray{{Valid: true, Bool: true}, {}} '{t,NULL}' [true,null] no text methods
TrimmedString("") '' "" empty
TrimmedString(" x ") 'x' "x" x
JSON(nil), JSON("") '{}' as []byte {} no text methods
Input Arrays TrimmedString JSON
SQL NULL empty slice error {}
SQL '' empty slice, error for StringArray "" {}
SQL '{}' empty slice the string {} {}
NULL element error, NULL element for NullBoolArray not an array not an array
JSON null empty slice "" the text null
JSON [] empty slice error the text []

Gotchas

  • Only the arrays turn SQL NULL into an empty value. TrimmedString.Scan(nil) returns can't scan <nil> as notnull.TrimmedString, and JSON.Scan(nil) stores {}.
  • JSON null is not mapped to {} by JSON: UnmarshalJSON stores the text null, which Value then writes as the JSON value null.
  • JSON(nil) is written as {}, an object, not as [], and JSON(nil).Valid() is true because it stands for the valid {}.
  • StringArray.Scan("") returns an error, the other arrays return an empty slice.
  • NULL elements fail in StringArray, IntArray and FloatArray: IntArray.Scan("{1,NULL}") returns an error. Only NullBoolArray has nullable elements, and it accepts t, f, true, false and NULL in any letter case.
  • notnull.NullBoolArray holds sql.NullBool elements, nullable.NullBoolArray holds nullable.Type[bool]. There is no notnull.BoolArray, NullIntArray or NullFloatArray.
  • notnull.TrimmedStringJoin keeps empty elements, nullable.TrimmedStringJoin skips them: TrimmedStringJoin(",", "a", " ", "b") returns a,,b here and a,b there.
  • Switching a field between notnull and nullable changes what a nil slice writes: '{}' here, NULL there.
  • encoding/json reads the keys of a map[TrimmedString]V trimmed, through UnmarshalText or UnmarshalJSON depending on the Go version, so " a" and "a" merge into one key. Use map[string]V to keep both.

Examples

A struct with never-null fields:

package main

import (
	"encoding/json"
	"fmt"

	"github.com/domonda/go-types/notnull"
)

type Document struct {
	Tags    notnull.StringArray   `json:"tags"`
	Pages   notnull.IntArray      `json:"pages"`
	Title   notnull.TrimmedString `json:"title"`
	Payload notnull.JSON          `json:"payload"`
}

func main() {
	// The zero value is written as empty arrays and an empty object, never null
	var doc Document
	j, _ := json.Marshal(doc)
	fmt.Println(string(j))

	tags, _ := doc.Tags.Value()
	payload, _ := doc.Payload.Value()
	fmt.Printf("%#v %s\n", tags, payload)

	// SQL NULL and JSON null read as empty, non-nil arrays
	var in Document
	err := json.Unmarshal([]byte(`{"tags":null,"pages":[1,2],"title":"  Report  "}`), &in)
	fmt.Println(err, in.Tags != nil, len(in.Tags), in.Pages, in.Title)
	fmt.Println(in.Pages.Scan(nil), in.Pages != nil, len(in.Pages))

	fmt.Printf("%q\n", notnull.TrimmedStringJoin(",", "a", " ", "b"))

	// Output:
	// {"tags":[],"pages":[],"title":"","payload":{}}
	// "{}" {}
	// <nil> true 0 [1, 2] Report
	// <nil> true 0
	// "a,,b"
}

Array literals:

package main

import (
	"fmt"

	"github.com/domonda/go-types/notnull"
)

func main() {
	elems, err := notnull.SplitArray(`{a,"b,c",NULL}`)
	fmt.Printf("%q %v\n", elems, err)
	values, err := notnull.SplitArrayValues(`{a,"b,c",NULL}`)
	fmt.Printf("%q %v\n", values, err)
	empty, err := notnull.SplitArray("NULL")
	fmt.Printf("%q %t %v\n", empty, empty != nil, err)

	fmt.Println(notnull.SQLArrayLiteral(nil))
	fmt.Println(notnull.SQLArrayLiteral([]string{"a", `b"c`}))

	var tags notnull.StringArray
	err = tags.Scan(notnull.SQLArrayLiteral([]string{"a", `b"c`}))
	fmt.Printf("%q %v\n", tags, err)

	// Output:
	// ["a" "\"b,c\"" "NULL"] <nil>
	// ["a" "b,c" "NULL"] <nil>
	// [] true <nil>
	// {}
	// {"a","b\"c"}
	// ["a" "b\"c"] <nil>
}

Documentation

Overview

Package notnull provides never-null counterparts of some types of package github.com/domonda/go-types/nullable, for NOT NULL columns and JSON fields that must not be null.

The zero value of every type is written as a value:

  • StringArray, IntArray, FloatArray and NullBoolArray write a nil slice as the empty PostgreSQL array '{}' and the JSON array []. Scan and UnmarshalJSON read SQL NULL and JSON null as a non-nil empty slice, so the arrays can be used without nil checks.
  • JSON writes nil as the empty JSON object {}.
  • TrimmedString trims every value and has no null state, the empty string is a value.

Use the nullable types instead where SQL NULL and JSON null must stay distinct from an empty value. Note that switching a field between the two packages changes what a nil slice is written as.

SplitArray, SplitArrayValues and SQLArrayLiteral parse and build PostgreSQL array literals and never return nil or NULL for an empty array.

See the README for tables of all functions and the exact serialization rules.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SQLArrayLiteral

func SQLArrayLiteral(s []string) string

SQLArrayLiteral joins the passed strings as an SQL array literal. Both a nil and an empty slice produce the empty array literal {} (use nullable.SQLArrayLiteral if a nil slice should produce NULL).

The result uses the PostgreSQL array text format ({"a","b"}), see https://www.postgresql.org/docs/current/arrays.html. That format is understood by PostgreSQL and array-compatible databases such as CockroachDB and YugabyteDB; databases without a native array type (MySQL, MariaDB, SQLite, SQL Server, Oracle) are not supported.

func SplitArray

func SplitArray(array string) ([]string, error)

SplitArray splits an SQL or JSON array into its top level elements. Array elements that are quoted strings will not be unquoted, use SplitArrayValues to get the values of quoted string elements. Returns a non nil empty slice in case of an empty array ("{}" or "[]") or when passing "null" or "NULL" as array.

An unquoted NULL element of an SQL array (null in a JSON array) is returned as the unquoted string "NULL" ("null").

A trailing comma announces an element that is not there and yields an empty string as last element. PostgreSQL rejects such a literal, this parser reports the announced element instead of dropping it silently.

func SplitArrayValues

func SplitArrayValues(array string) ([]string, error)

SplitArrayValues splits an SQL or JSON array into its top level elements like SplitArray and returns the value of every element that is a double quoted string with the quotes removed and the escape sequences of the parsed array syntax undone. Returns a non nil empty slice in case of an empty array ("{}" or "[]") or when passing "null" or "NULL" as array.

A backslash escapes the following character in a PostgreSQL array element whether it is quoted or not, so every element of an SQL array is unescaped. In a JSON array only double quoted strings are, every other element, like the objects of a JSON array of objects, is returned unchanged.

An unquoted NULL element of an SQL array (null in a JSON array) is returned as the string "NULL" ("null") and is indistinguishable from a quoted "NULL" ("null") string element. Use SplitArray to tell them apart, its elements correspond by index and a quoted element still has its quotes there.

Returns an error for a quoted element of a JSON array that is not a valid JSON string, like one with an invalid escape sequence.

Types

type FloatArray

type FloatArray []float64

FloatArray implements the sql.Scanner and driver.Valuer interfaces for a slice of float64. The nil default value of the slice is returned as an empty (non null) array for SQL and JSON. Use nullable.FloatArray if the nil value should be treated as SQL and JSON null.

Value and Scan use the PostgreSQL array text format ({1.5,2,3}), see https://www.postgresql.org/docs/current/arrays.html. That format is understood by PostgreSQL and array-compatible databases such as CockroachDB and YugabyteDB; databases without a native array type (MySQL, MariaDB, SQLite, SQL Server, Oracle) are not supported.

func (FloatArray) Contains

func (a FloatArray) Contains(value float64) bool

Contains reports if the passed value is present in a.

func (FloatArray) Len

func (a FloatArray) Len() int

Len is the number of elements in the collection. One of the methods to implement sort.Interface.

func (FloatArray) Less

func (a FloatArray) Less(i, j int) bool

Less reports whether the element with index i should sort before the element with index j. One of the methods to implement sort.Interface.

func (FloatArray) MarshalJSON

func (a FloatArray) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler. A nil or empty array is encoded as the empty JSON array [] instead of null; a notnull array is never null. JSON has no NaN or infinity, so like encoding/json it returns a *json.UnsupportedValueError for them.

func (*FloatArray) Scan

func (a *FloatArray) Scan(src any) error

Scan implements the sql.Scanner interface. It parses a PostgreSQL float array literal like {1.5,2,3} from a string or []byte. A nil source (SQL NULL), an empty string, or {} all scan to a non-nil empty slice; a notnull array is never nil.

func (FloatArray) String

func (a FloatArray) String() string

String implements the fmt.Stringer interface.

func (FloatArray) Swap

func (a FloatArray) Swap(i, j int)

Swap swaps the elements with indexes i and j. One of the methods to implement sort.Interface.

func (*FloatArray) UnmarshalJSON

func (a *FloatArray) UnmarshalJSON(data []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler. JSON null and [] both unmarshal to a non-nil empty slice; a notnull array is never nil.

func (FloatArray) Value

func (a FloatArray) Value() (driver.Value, error)

Value implements the database/sql/driver.Valuer interface. It returns the slice as a PostgreSQL float array literal like {1.5,2,3}. A nil or empty slice returns the empty array {}.

type IntArray

type IntArray []int64

IntArray implements the sql.Scanner and driver.Valuer interfaces for a slice of int64. The nil default value of the slice is returned as an empty (non null) array for SQL and JSON. Use nullable.IntArray if the nil value should be treated as SQL and JSON null.

Value and Scan use the PostgreSQL array text format ({1,2,3}), see https://www.postgresql.org/docs/current/arrays.html. That format is understood by PostgreSQL and array-compatible databases such as CockroachDB and YugabyteDB; databases without a native array type (MySQL, MariaDB, SQLite, SQL Server, Oracle) are not supported.

func (IntArray) Contains

func (a IntArray) Contains(value int64) bool

Contains reports if the passed value is present in a.

func (IntArray) Len

func (a IntArray) Len() int

Len is the number of elements in the collection. One of the methods to implement sort.Interface.

func (IntArray) Less

func (a IntArray) Less(i, j int) bool

Less reports whether the element with index i should sort before the element with index j. One of the methods to implement sort.Interface.

func (IntArray) MarshalJSON

func (a IntArray) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler. A nil or empty array is encoded as the empty JSON array [] instead of null; a notnull array is never null.

func (*IntArray) Scan

func (a *IntArray) Scan(src any) error

Scan implements the sql.Scanner interface. It parses a PostgreSQL integer array literal like {1,2,3} from a string or []byte. A nil source (SQL NULL), an empty string, or {} all scan to a non-nil empty slice; a notnull array is never nil.

func (IntArray) String

func (a IntArray) String() string

String implements the fmt.Stringer interface.

func (IntArray) Swap

func (a IntArray) Swap(i, j int)

Swap swaps the elements with indexes i and j. One of the methods to implement sort.Interface.

func (*IntArray) UnmarshalJSON

func (a *IntArray) UnmarshalJSON(data []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler. JSON null and [] both unmarshal to a non-nil empty slice; a notnull array is never nil.

func (IntArray) Value

func (a IntArray) Value() (driver.Value, error)

Value implements the database/sql/driver.Valuer interface. It returns the slice as a PostgreSQL integer array literal like {1,2,3}. A nil or empty slice returns the empty array {}.

type JSON

type JSON []byte

JSON is a []byte slice containing JSON text. JSON(nil) is interpreted as an empty json object: {} Implements the interfaces json.Marshaler, json.Unmarshaler, driver.Valuer and sql.Scanner. Use nullable.JSON if the JSON(nil) value should be interpreted as JSON "null" and SQL "NULL".

func MarshalJSON

func MarshalJSON(source any) (JSON, error)

MarshalJSON marshals source as JSON and returns it as a notnull JSON value.

func (JSON) Clone

func (j JSON) Clone() JSON

Clone returns a copy of j. A nil j returns nil, so the clone also encodes as {}.

func (JSON) GoString

func (j JSON) GoString() string

GoString returns a Go syntax representation of j as a notnull.JSON literal. GoString implements the fmt.GoStringer interface.

func (JSON) IsEmpty

func (j JSON) IsEmpty() bool

IsEmpty returns true if j is nil, or an empty JSON value like "", "{}", or "[]"

func (*JSON) MarshalFrom

func (j *JSON) MarshalFrom(source any) error

MarshalFrom marshals source as JSON and sets it at j when there was no error.

func (JSON) MarshalJSON

func (j JSON) MarshalJSON() ([]byte, error)

MarshalJSON returns j as the JSON encoding of j. A nil or empty j holds no JSON text and returns {}. MarshalJSON implements encoding/json.Marshaler See the package function MarshalJSON to marshal a struct into JSON

func (JSON) PrettyPrint

func (j JSON) PrettyPrint(w io.Writer) (int, error)

PrettyPrint implements the pretty.PrintableWithResult interface returning the JSON as a Go literal.

func (*JSON) Scan

func (j *JSON) Scan(src any) error

Scan stores the src in *j. No validation is done. SQL NULL and an empty string or []byte, which hold no JSON text, store the empty object {}.

func (JSON) String

func (j JSON) String() string

String returns the JSON as string, or {} for a nil or empty j. String implements the fmt.Stringer interface.

func (*JSON) UnmarshalJSON

func (j *JSON) UnmarshalJSON(sourceJSON []byte) error

UnmarshalJSON sets *j to a copy of sourceJSON. The JSON null value is stored as the text null, not as nil. UnmarshalJSON implements encoding/json.Unmarshaler See method UnmarshalTo for unmarshalling into a struct.

func (JSON) UnmarshalTo

func (j JSON) UnmarshalTo(dest any) error

UnmarshalTo unmarshals the JSON of j to dest. A nil or empty j is unmarshalled as the empty object {}.

func (JSON) Valid

func (j JSON) Valid() bool

Valid reports whether j is a valid JSON encoding. A nil or empty j is valid because it stands for the empty object {} that MarshalJSON and Value write.

func (JSON) Value

func (j JSON) Value() (driver.Value, error)

Value returns j as a SQL value. A nil or empty JSON is written as the empty object {} like MarshalJSON writes it.

type NullBoolArray

type NullBoolArray []sql.NullBool

NullBoolArray implements the sql.Scanner and driver.Valuer interfaces for a slice of sql.NullBool. The nil default value of the slice is returned as an empty (non null) array for SQL and JSON. Use nullable.NullBoolArray if the nil value should be treated as SQL and JSON null.

Value and Scan use the PostgreSQL array text format ({t,f,NULL}), see https://www.postgresql.org/docs/current/arrays.html. That format is understood by PostgreSQL and array-compatible databases such as CockroachDB and YugabyteDB; databases without a native array type (MySQL, MariaDB, SQLite, SQL Server, Oracle) are not supported.

func (NullBoolArray) Bools

func (a NullBoolArray) Bools() []bool

Bools returns all NullBoolArray elements as []bool with NULL elements set to false.

func (NullBoolArray) MarshalJSON

func (a NullBoolArray) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler. Valid elements are encoded as JSON true or false, invalid (NULL) elements as JSON null. A nil or empty array is encoded as the empty JSON array [] instead of null; a notnull array is never null.

func (*NullBoolArray) Scan

func (a *NullBoolArray) Scan(src any) error

Scan implements the sql.Scanner interface. It parses a PostgreSQL boolean array literal like {t,f,NULL} from a string or []byte. The elements t, f, true and false scan as valid and NULL as an invalid sql.NullBool, all case-insensitive. Any other element returns an error and leaves a unchanged. A nil source (SQL NULL), an empty string, or {} all scan to a non-nil empty slice; a notnull array is never nil.

func (NullBoolArray) String

func (a NullBoolArray) String() string

String implements the fmt.Stringer interface.

func (*NullBoolArray) UnmarshalJSON

func (a *NullBoolArray) UnmarshalJSON(data []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler. JSON null and [] both unmarshal to a non-nil empty slice; a notnull array is never nil. JSON null elements unmarshal to an invalid sql.NullBool.

func (NullBoolArray) Value

func (a NullBoolArray) Value() (driver.Value, error)

Value implements the database/sql/driver.Valuer interface. It returns the slice as a PostgreSQL boolean array literal like {t,f,NULL}, with invalid (NULL) elements written as NULL. A nil or empty slice returns the empty array {}.

type StringArray

type StringArray []string

StringArray implements the sql.Scanner, driver.Valuer, and encoding/json.Marshaler interfaces for a slice of strings. The nil default value of the slice is returned as an empty (non null) array for SQL and JSON. Use nullable.StringArray if the nil value should be treated as SQL and JSON null.

Value and Scan use the PostgreSQL array text format ({"a","b"}), see https://www.postgresql.org/docs/current/arrays.html. That format is understood by PostgreSQL and array-compatible databases such as CockroachDB and YugabyteDB; databases without a native array type (MySQL, MariaDB, SQLite, SQL Server, Oracle) are not supported.

func (StringArray) Contains

func (a StringArray) Contains(value string) bool

Contains reports if the passed value is present in a.

func (StringArray) Len

func (a StringArray) Len() int

Len is the number of elements in the collection. One of the methods to implement sort.Interface.

func (StringArray) Less

func (a StringArray) Less(i, j int) bool

Less reports whether the element with index i should sort before the element with index j. One of the methods to implement sort.Interface.

func (StringArray) MarshalJSON

func (a StringArray) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler. A nil or empty array is encoded as the empty JSON array [] instead of null; a notnull array is never null.

func (*StringArray) Scan

func (a *StringArray) Scan(src any) error

Scan implements the sql.Scanner interface. It parses a PostgreSQL text array literal like {"a","b"} (quoted or unquoted elements) from a string or []byte. A nil source (SQL NULL) or {} scan to a non-nil empty slice; a notnull array is never nil.

func (StringArray) Swap

func (a StringArray) Swap(i, j int)

Swap swaps the elements with indexes i and j. One of the methods to implement sort.Interface.

func (*StringArray) UnmarshalJSON

func (a *StringArray) UnmarshalJSON(data []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler. JSON null and [] both unmarshal to a non-nil empty slice; a notnull array is never nil.

func (StringArray) Value

func (a StringArray) Value() (driver.Value, error)

Value implements the driver.Valuer interface. It returns the slice as a PostgreSQL text array literal like {"a","b"} with each element quoted and escaped. A nil or empty slice returns the empty array {}.

type TrimmedString

type TrimmedString string

TrimmedString is a string type where all marshaller and unmarshaller will trim whitespace first before returning or using a value. TrimmedString can hold an empty string.

func TrimmedStringFrom

func TrimmedStringFrom(str string) TrimmedString

TrimmedStringFrom trims the passed str and returns it as TrimmedString

func TrimmedStringJoin

func TrimmedStringJoin[S ~string](separator string, strs ...S) TrimmedString

TrimmedStringJoin joins trimmed strings with the passed separator between them. Unlike nullable.TrimmedStringJoin it keeps strings that are empty after trimming.

func TrimmedStringf

func TrimmedStringf(format string, a ...any) TrimmedString

TrimmedStringf formats a string using fmt.Sprintf and returns it as TrimmedString.

func (TrimmedString) Contains

func (s TrimmedString) Contains(substr string) bool

Contains reports whether substr is within s.

func (TrimmedString) ContainsAny

func (s TrimmedString) ContainsAny(chars string) bool

ContainsAny reports whether any Unicode code points in chars are within s.

func (TrimmedString) ContainsRune

func (s TrimmedString) ContainsRune(r rune) bool

ContainsRune reports whether the Unicode code point r is within s.

func (TrimmedString) HasPrefix

func (s TrimmedString) HasPrefix(prefix string) bool

HasPrefix tests whether the TrimmedString begins with prefix.

func (TrimmedString) HasSuffix

func (s TrimmedString) HasSuffix(suffix string) bool

HasSuffix tests whether the TrimmedString ends with suffix.

func (TrimmedString) IsEmpty

func (s TrimmedString) IsEmpty() bool

IsEmpty indicates if the trimmed string is empty which is also the case when the underlying string consists only of runes removed by strutil.TrimSpace.

func (TrimmedString) MarshalJSON

func (s TrimmedString) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler

func (TrimmedString) MarshalText

func (s TrimmedString) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface

func (TrimmedString) MarshalXML

func (s TrimmedString) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML implements encoding/xml.Marshaler by encoding the trimmed string as the character data of an XML element.

func (*TrimmedString) MarshalXMLAttr

func (s *TrimmedString) MarshalXMLAttr(name xml.Name) (xml.Attr, error)

MarshalXMLAttr implements encoding/xml.MarshalerAttr by writing the text of MarshalText, and no attribute for a nil pointer, because encoding/xml calls MarshalText through a nil pointer attribute field and panics.

func (TrimmedString) ReplaceAll

func (s TrimmedString) ReplaceAll(old, new string) TrimmedString

ReplaceAll returns a copy of the TrimmedString with all non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string.

func (*TrimmedString) Scan

func (s *TrimmedString) Scan(value any) error

Scan implements the database/sql.Scanner interface. SQL NULL returns an error because TrimmedString has no null state, use nullable.TrimmedString for nullable columns.

func (*TrimmedString) Set

func (s *TrimmedString) Set(str string)

Set the passed string as TrimmedString

func (TrimmedString) Split

func (s TrimmedString) Split(sep string) []TrimmedString

Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators.

If s does not contain sep and sep is not empty, Split returns a slice of length 1 whose only element is s.

If sep is empty, Split splits after each UTF-8 sequence. If both s and sep are empty, Split returns an empty slice.

It is equivalent to SplitN with a count of -1.

To split around the first instance of a separator, see Cut.

func (TrimmedString) String

func (s TrimmedString) String() string

String implements the fmt.Stringer interface by returning a trimmed string that might be empty if the underlying string consists only of whitespace.

func (TrimmedString) ToLower

func (s TrimmedString) ToLower() TrimmedString

ToLower returns s with all Unicode letters mapped to their lower case.

func (TrimmedString) ToUpper

func (s TrimmedString) ToUpper() TrimmedString

ToUpper returns s with all Unicode letters mapped to their upper case.

func (TrimmedString) ToValidUTF8

func (s TrimmedString) ToValidUTF8(replacement string) TrimmedString

ToValidUTF8 returns a copy of the TrimmedString with each run of invalid UTF-8 byte sequences replaced by the replacement string, which may be empty.

func (TrimmedString) TrimPrefix

func (s TrimmedString) TrimPrefix(prefix string) TrimmedString

TrimPrefix returns s without the provided leading prefix string. If the TrimmedString doesn't start with prefix, s is returned unchanged.

func (TrimmedString) TrimSuffix

func (s TrimmedString) TrimSuffix(suffix string) TrimmedString

TrimSuffix returns s without the provided trailing suffix string. If the TrimmedString doesn't end with suffix, s is returned unchanged.

func (*TrimmedString) UnmarshalJSON

func (s *TrimmedString) UnmarshalJSON(j []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler

func (*TrimmedString) UnmarshalText

func (s *TrimmedString) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface

func (*TrimmedString) UnmarshalXML

func (s *TrimmedString) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements encoding/xml.Unmarshaler by decoding the character data of the XML element, trimming whitespace, and storing the result.

func (TrimmedString) Value

func (s TrimmedString) Value() (driver.Value, error)

Value implements the driver database/sql/driver.Valuer interface

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL