Skip to content

csmu-cenr/go-nullable

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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)

About

Nullable type for Go

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Go 100.0%