0
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] 構造体のKey/Value を出力する

Posted at
package main

import (
	"fmt"
	"reflect"
)

type User struct {
	ID  string
	Foo string
	Bar int
	pri string
	Pub int
}

func main() {
	user := User{"id1", "foo", 2, "skip me without panic", 4}
	fmt.Println(user.String())
	//ID: id1
	//Foo: foo
	//Bar: 2
	//Pub: 4
}

func (u User) String() string {
	str := ""
	fa := reflect.ValueOf(u)
	for i := 0; i < fa.NumField(); i++ {
		if !fa.Field(i).CanInterface() { // skip private for avoid panic
			continue
		}
		str += fmt.Sprintf("%v: %v\n", fa.Type().Field(i).Name, fa.Field(i).Interface())
	}
	return str
}

REF

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?