31
24

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 5 years have passed since last update.

Go で interface {} の中身がポインタならその参照先を取得する

Last updated at Posted at 2016-01-30

文字列を渡しても文字列へのポインタを渡しても、文字列を得る方法。

例えば関数の引数として interface {} な変数を受け取ったとして、
その中身が文字列 "abc" ならその値を、中身が文字列 "abc" へのポインタならその参照先である "abc" を取得する。

func dereferenceIfPtr(value interface{}) interface{} {
	return reflect.Indirect(reflect.ValueOf(value)).Interface()
}

実行例は以下の場所にあります。
https://play.golang.org/p/U6_5C16O-rI

以前書いていたモノ

func dereferenceIfPtr(value interface{}) interface{} {
	if reflect.TypeOf(value).Kind() == reflect.Ptr {
		return reflect.ValueOf(value).Elem().Interface()
		//return *value
		//=> invalid indirect of value (type interface {})
	} else {
		return value
	}
}

実行例は以下の場所にあります。
https://play.golang.org/p/1vFSqzDmA0

31
24
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
31
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?