Go 오브젝트 해시

개요[ | ]

Go 오브젝트 해시
package main

import (
	"crypto/sha256"
	"fmt"
)

type Foo struct {
	id   int
	name string
}

func main() {
	fmt.Println(Hash(1))   // dddf34d03a11c85d73a2da4a2fbccbab8dae67206e6d821a4db1ab91e375325c
	fmt.Println(Hash("1")) // 3374de636d7ca0d2cc16bea4ffe26a1994ff2f24f5b49cad2e44bfee6586961e

	fmt.Println(Hash([]int{1, 2, 3})) // ba51b372c6f8af6307e305c716d745ea1bbdfb60601d53aa31d96224c0c09e83
	fmt.Println(Hash([]int{3, 2, 1})) // 45f3f718a604a286772e6e5b86049c3d92f87c3d9b8b770867090516ae81e35c

	fmt.Println(Hash(1, "2", []int{3})) // 10bf3c7c44ff78daf95c0c248eeec80b0afc97c5ccf97c2052a338b13cda3ff1

	// map
	fmt.Println(Hash(map[string]int{"a": 1, "b": 2})) // f50028039f1a430593f0fb14622f46fd41f1765e4b282f911df0d3299116ce72
	fmt.Println(Hash(map[string]int{"b": 2, "a": 1})) // f50028039f1a430593f0fb14622f46fd41f1765e4b282f911df0d3299116ce72

	// struct
	fmt.Println(Hash(Foo{name: "Alice", id: 1})) // 076c3eeb66efe38506b1e8f1016c6e8f76085452065aa05e04a3ec2f34311c7d
	fmt.Println(Hash(Foo{id: 1, name: "Alice"})) // 076c3eeb66efe38506b1e8f1016c6e8f76085452065aa05e04a3ec2f34311c7d

}

func Hash(objs ...interface{}) string {
	h := sha256.New()
	fmt.Fprintf(h, "%#v", objs)
	return fmt.Sprintf("%x", h.Sum(nil))
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}