LoginSignup
5
3

More than 5 years have passed since last update.

reflectとinterface型の威力

Last updated at Posted at 2018-03-06

目的

非常に簡単な例を用いて、reflectinterface{}の便利さを知る

簡単な例

例えば、こんな感じにstructが定義されているとする。

type ParamA struct {
    UserID   string
    Contents string
}

type ParamB struct {
    UserID string
    Price  int
}

type ParamC struct {
    UserID string
    IsLike bool
}

この時、UserIDを抽出する処理をどう書くか、という話

普通の書き方

単純に書くとこうなる

func A_API(p ParamA) {
    uid := ParamA.UserID
}

func B_API(p ParamB) {
    uid := ParamB.UserID
}

func C_API(p ParamC) {
    uid := ParamC.UserID
}

reflectとinterface{}を使った書き方

paramからUserIDの値を抜き出す処理」をメソッド化してみる

func A_API(p paramA) {
    uid := getUserID(p)
}

func B_API(p paramB) {
    uid := getUserID(p)
}

func C_API(p paramC) {
    uid := getUserID(p)
}

func getUserID(s interface{}) string {
    ref := reflect.ValueOf(s)
    userID := ref.FieldByName("UserID").Interface()
    uid, err := userID.(string)
    // TODO: エラーハンドリング

    return uid
}
5
3
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
5
3