LoginSignup
0
0

More than 3 years have passed since last update.

Go言語でoptinal型もどきを使う

Posted at

はじめに

go言語を使用していて、optionalが使えなくて困ったため。
ライブラリを入れる程ではないので、以下のコードを参考に書いてみた。
参考 https://github.com/markphelps/optional

実装したメソッドの概要

NewInt(i int) optional.Int

optional型を作成する。

Get() (int, bool)

optinalの中身を取り出す。値が存在するときは、value true, ないときは、0, falseを返す。

Set(i int)

optionalに値を設定する。

Present() bool

値があるか、どうかをチェックする。

コードの中身

package optional

// Int - optional int
type Int struct {
    value *int
}

// NewInt - create an optional.Int from int
func NewInt(i int) Int {
    return Int{value: &i}
}

// Get - get the wrapped value
func (i Int) Get() (int, bool) {
    if i.Present() {
        return *i.value, true
    }
    var zero int
    return zero, false
}

// Set - set value
func (i Int) Set(j int) {
    i.value = &j
}

// Present - return whether or not the value is present.
func (i Int) Present() bool {
    return i.value != nil
}

あとがき

簡単な実装ですが、optionalっぽいことができてよかった。
optional.Int{}でNoneの状態が書けるのがよいです。
jsonにデコードしたり、他の型でのoptionalが欲しい場合は、https://github.com/markphelps/optional をインポートすると良いと思います。

0
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
0
0