orderedobject

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2024 License: MIT Imports: 2 Imported by: 1

README

orderedobject

Go Reference

orderedobject is a simple Go package that provides an Object type for representing JSON objects that respect insertion order. It uses generics to allow for type-safe usage with any value type.

Installation

To install the package, use go get:

go get github.com/Hyper-Solutions/orderedobject

Usage

Here's a simple usage example:

package main

import (
    "encoding/json"
    "fmt"

    "github.com/Hyper-Solutions/orderedobject"
)

func main() {
    // Create a new object with a capacity of 3
    obj := orderedobject.NewObject[any](3)

    // Set key-value pairs
    obj.Set("name", "John")
    obj.Set("age", 30)
    obj.Set("city", "New York")

    // Marshal the object to JSON
    encoded, err := json.Marshal(obj)
    if err != nil {
        panic(err)
    }

    fmt.Println(string(encoded))
    // Output: {"name":"John","age":30,"city":"New York"}
}

The Object type provides the following methods:

  • NewObject[V any](capacity int) *Object[V]: Creates a new Object with the specified capacity.
  • Set(key string, value V): Sets a key-value pair in the object. If the key already exists, its value is replaced.
  • Has(key string) bool: Checks if a key is set in the object.
  • Get(key string) V: Retrieves the value associated with a key. If the key is not set, the zero value of type V is returned.
  • MarshalJSON() ([]byte, error): Marshals the object to JSON, respecting the insertion order of key-value pairs.

License

This package is licensed under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Object

type Object[V any] []*Pair[V]

Object represents a JSON object that respects insertion order.

func NewObject

func NewObject[V any](capacity int) *Object[V]

NewObject creates a new Object with the specified capacity.

func (*Object[V]) Get

func (object *Object[V]) Get(key string) V

Get gets the value of key.

The returned value is V's zero value if key isn't set.

func (*Object[V]) Has

func (object *Object[V]) Has(key string) bool

Has reports if the given key is set.

func (*Object[V]) MarshalJSON

func (object *Object[V]) MarshalJSON() ([]byte, error)

MarshalJSON encodes the object into JSON format, respecting insertion order in the process.

func (*Object[V]) Set

func (object *Object[V]) Set(key string, value V)

Set sets key in object with the given value.

The key is replaced if it already exists.

type Pair

type Pair[V any] struct {
	// Key is the pair's key.
	Key string

	// Value is the pair's value.
	Value V
}

Pair represents a key value pair.

Jump to

Keyboard shortcuts

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