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
}
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme