gohashcode

package module
v0.0.0-...-532ff59 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2024 License: MIT Imports: 4 Imported by: 0

README

gohashcode GoDoc

gohashcode is a Go library for generating a unique hash value for arbitrary values in Go.

This can be used to key values in a hash (for use in a map, set, etc.) that are complex. The most common use case is comparing two values without particular fields, caching values, de-duplication, and so on.

Features

  • Hash any arbitrary Go value, including complex types.

  • Tag a struct field to ignore it and not affect the hash value.

  • Optionally, override the hashing process by implementing Hashcoder to optimize for speed, collision avoidance for your data set, etc.

Installation

$ go get github.com/okhomin/gohashcode

Usage & Example

For usage and examples see the Godoc

A quick code example is shown below:

type S struct {
	A int
	B string
	C string `hash:"-"`     // ignore
	E string `hash:"false"` // ignore
	F []uint
	G map[string]uint
}

hash := gohashcode.Hashcode(S{
	A: 123,
	B: "Hello",
	C: "Ignore",
	E: "Ignore",
	F: []uint{1, 2, 3},
	G: map[string]uint{
		"one": 1,
		"two": 2,
	},
})

fmt.Println(hash)
// Output:
// 2377125169852

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Hashcode

func Hashcode(v any) uint64

Hashcode returns a hashcode of v Hashcode traverses the value v recursively. If an encountered value implements Hashcoder and is not a nil pointer, Hashcode calls [Hashcoder.Hashcode] to compute the hashcode of the value. Otherwise, Hashcode uses the default hashcode algorithm.

Example
package main

import (
	"fmt"
	"github.com/okhomin/gohashcode"
)

func main() {
	type S struct {
		A int
		B string
		C string `hash:"-"`     // ignore
		E string `hash:"false"` // ignore
		F []uint
		G map[string]uint
	}

	hash := gohashcode.Hashcode(S{
		A: 123,
		B: "Hello",
		C: "Ignore",
		E: "Ignore",
		F: []uint{1, 2, 3},
		G: map[string]uint{
			"one": 1,
			"two": 2,
		},
	})

	fmt.Println(hash)
}

Types

type Hashcoder

type Hashcoder interface {
	Hashcode() uint64
}

Hashcoder is the interface implemented by types that can compute their own valid hashcode.

Jump to

Keyboard shortcuts

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