3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Go]文字列をhashにして数字として取得したい

Last updated at Posted at 2020-08-26

何かしらの文字列からhashを作成する事はそんなに難しくないと思いますが
hashを数字として取得したい事があると思います。
そんな時には hash/fnv#Sum32()が使用出来ます。

以下は「文字列を入力して特定の色typeを返す」サンプルです。

package main

import (
	"fmt"
	"hash/fnv"
)

type COLOR uint32

const (
	COLOR_RED    COLOR = 0
	COLOR_BLUE   COLOR = 1
	COLOR_GREEN  COLOR = 2
	COLOR_PURPLE COLOR = 3
	COLOR_BROWN  COLOR = 4
)

func (c COLOR) String() string {
	switch c {
	case COLOR_RED:
		return "RED"
	case COLOR_BLUE:
		return "BLUE"
	case COLOR_GREEN:
		return "GREEN"
	case COLOR_PURPLE:
		return "PURPLE"
	case COLOR_BROWN:
		return "BROWN"
	}
	return ""
}

func color(s string) COLOR {
	h := fnv.New32a()
	h.Write([]byte(s))
	return COLOR(h.Sum32() % 5)
}

func main() {
	fmt.Println(color("hogehoge"))
	fmt.Println(color("fugafuga"))
	fmt.Println(color("piyopiyo"))
}

実行すると以下のように毎回同じCOLOR typeが取得できます。

BLUE
RED
GREEN
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?