LoginSignup
3
1

More than 5 years have passed since last update.

goで関数内に定義した構造体をインタフェースで戻してフィールドを表示してみたメモ

Last updated at Posted at 2017-10-19

関数内に構造体を定義してインタフェースで戻してフィールドと値を出力した時のメモです。

package main

import (
    "fmt"
    "reflect"
)

// 自己紹介関数
func selfIntroduction() (i interface{}) {
    // 個人情報構造体
    type personalInfomation struct {
        Name   string
        LiveIn string
        Job    string
    }
    r := new(personalInfomation)
    r.Name = "sky_jokerxx"
    r.LiveIn = "Tokyo"
    r.Job = "office worker"
    return r
}

func main() {
    r := selfIntroduction()
    v := reflect.Indirect(reflect.ValueOf(r))
    t := v.Type()
    for i := 0; i < t.NumField(); i++ {
        fmt.Println(t.Field(i).Name + ": " + v.Field(i).String())
    }
}

参考

3
1
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
1