2
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?

Goのリクエストパラメータでpointer型とnull.Stringのどちらを使うべきか

2
Posted at

今回の状況ではpointerが妥当だと言う結論になりました。

前提としては以下です

  • nullとstring(空文字を含む)を区別する
  • パラメータがリクエストにあるか、値がnullであるかは区別しない
  • この値をDBに保存しない

背景

リクエストオブジェクトのパラメータの型でpointerとnull許容の型どちらを使うのが良いか悩んだ為です。

前提としては以下です

  • nullとstring(空文字を含む)を区別する
  • パラメータがリクエストにあるか、値がnullであるかは区別しない
  • この値をDBに保存しない
import (
    "gopkg.in/guregu/null.v4"
)

type SampleRequest struct {
    From                 null.String            `json:"from"`
    To                   *string                `json:"to"`
}

nullパッケージとは

NULL許容のSQLおよびJSON値を扱うためのライブラリです。

null.String型の値は以下のようになっています。

jsonに変換される場合の値
null null
null以外 string

ゼロ値(stringで言うと空文字)とnullを別々の値として扱う必要がある場合に有効だそうです。

type SampleRequest struct {
    From                 null.String            `json:"from"`
}

null.String型は以下のような構造体です

type String struct {
	sql.NullString
}

type NullString struct {
	String string
	Valid  bool // Valid is true if String is not NULL
}

Stringがnullでない場合、ValidはTrueになります

よって値があるかの判定は以下になります。

if(p.From.Valid) {
}

pointerとは

変数の値のアドレスです。
ゼロ値はnilです。

type SampleRequest struct {
    From                 *string            `json:"from"`

値があるかの判定は以下です。

if p.From != nil {
}

最小コストで済むのはpointer

今回の用途だと以下を区別する必要がないのでpointerで十分と考えました。

  • 空文字であるか、nullであるか
  • パラメータがリクエストにあるか、値がnullであるか

参考

2
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
2
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?