go-nullable

module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2022 License: MIT

README

Go Nullable GoDoc

import "github.com/Uffe-Code/go-nullable/nullable"

go-nullable is a library that desires to enable null-able support for struct and primitive types.

It is inspired by the way .NET solves it, and by https://github.com/guregu/null.

This package mainly exposes the struct Nullable[T] which will work in the same manner as the nullable type in C#. It exposes two properties, the boolean IsValid and the actual Data.

The struct implements encoding.TextMarshaler, encoding.TextUnmarshaler, json.Marshaler and json.Unmarshaler. It also implements sql.Scanner and sql.Valuer so it supports usage in SQL. A null object's MarshalText will return a blank string.

Struct signature

The struct looks just like nullable data types in .NET.

package main

import (
	"fmt"
	"github.com/Uffe-Code/go-nullable/nullable"
)

func main() {
	n := nullable.Null[int16]()
	n.IsValid // is FALSE
	n.Data    // is just default value (0)

	m := nullable.Value(10)
	m.IsValid // is TRUE
	m.Data    // is 10

	str := fmt.Sprintf("%s", m) // will be "10"
}

Usage

This type can be used as properties for API structs.

type Task struct {
  TaskId    int                    `json:"task_id"`
  ProjectId nullable.Nullable[int] `json:"project_id"`
  Subject   string                 `json:"subject"`
}

This struct can be read and written to JSON as expected.

{
  "task_id": 5,
  "project_id": null,
  "subject": "Task"
}

will be represented as

task := task{
  TaskId: 5,
  ProjectId: nullable.Null[int]()
  Subject: "Task",
}

and if we have a value in ProjectId it will look like this:

task := task{
  TaskId: 5,
  ProjectId: nullable.Value(10),
  Subject: "Task",
}

The task can be marshalled to JSON normally:

jsonData, err := json.Marshal(task)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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