fork download
  1. package main
  2.  
  3. import (
  4. "bufio"
  5. "fmt"
  6. "os"
  7. "reflect"
  8. "regexp"
  9. "strings"
  10. )
  11.  
  12. type Profile struct {
  13. mine MyProfile "My datas"
  14. yours YourProfile "Your datas"
  15. }
  16.  
  17. type MyProfile struct {
  18. Name string
  19. Email string
  20. Phone string
  21. Occupation []string
  22. Language []string
  23. Hobby []string
  24. }
  25.  
  26. type YourProfile struct {
  27. Name string
  28. Gender string
  29. }
  30.  
  31. func NewProfile(arr map[string]map[string]interface{}) *Profile {
  32. return &Profile{
  33. mine: SetProfile(MyProfile{}, arr["me"]).(MyProfile),
  34. yours: SetProfile(YourProfile{}, arr["you"]).(YourProfile),
  35. }
  36. }
  37.  
  38. type M interface {
  39. ShowMessage() string
  40. }
  41.  
  42. func (p *Profile) ShowMessage() string {
  43. return fmt.Sprintf("Hi, %s. \nName: %s \nLanguage: %s", p.yours.Name, p.mine.Name,
  44. strings.Join(p.mine.Language, ", "))
  45. }
  46.  
  47. func SetProfile(p interface{}, arr map[string]interface{}) interface{} {
  48. pst := reflect.New(reflect.TypeOf(p))
  49. for k, v := range arr {
  50. key := pst.Elem().FieldByName(k)
  51. if key.IsValid() && key.CanSet() {
  52. key.Set(reflect.ValueOf(v))
  53. }
  54. }
  55. return pst.Elem().Interface()
  56. }
  57.  
  58. func ArrangeAnswer(ans string) string {
  59. re := regexp.MustCompile(`(\s| )+`)
  60. return strings.TrimSpace(re.ReplaceAllString(ans, " "))
  61. }
  62.  
  63. func main() {
  64. prof := make(map[string]map[string]interface{})
  65.  
  66. prof["me"] = map[string]interface{}{
  67. "Name": "John Lennon",
  68. "Email": "foobar@gmail.com",
  69. "Phone": "+81-90-0000-0000",
  70. "Occupation": []string{"Programmer", "System Engineer"},
  71. "Language": []string{"Go", "Java", "Python", "PHP", "JavaScript", "C"},
  72. }
  73. prof["you"] = make(map[string]interface{})
  74.  
  75. scanner := bufio.NewScanner(os.Stdin)
  76. fmt.Println("Would you please let me know your profile?")
  77. for {
  78. fmt.Print("Your name: ")
  79. scanner.Scan()
  80. ans := ArrangeAnswer(scanner.Text())
  81. re := regexp.MustCompile(`^[a-zA-Z ]+$`)
  82. if re.MatchString(ans) {
  83. prof["you"]["Name"] = ans
  84. break
  85. } else {
  86. fmt.Println("alphabet please.")
  87. }
  88. }
  89. fmt.Print("Your gender: ")
  90. scanner.Scan()
  91. prof["you"]["Gender"] = strings.ToLower(ArrangeAnswer(scanner.Text()))
  92. if err := scanner.Err(); err != nil {
  93. fmt.Fprintln(os.Stderr, "Read error: ", err)
  94. }
  95.  
  96. p := NewProfile(prof)
  97. fmt.Println(p.ShowMessage())
  98. }
  99.  
Success #stdin #stdout 0s 790016KB
stdin
Alice
Female
stdout
Would you please let me know your profile?
Your name: Your gender: Hi, Alice. 
Name: John Lennon 
Language: Go, Java, Python, PHP, JavaScript, C