Created
          June 18, 2021 06:40 
        
      - 
      
- 
        Save umkh/5d46b8e12bde20ddb372ee44db0b64c0 to your computer and use it in GitHub Desktop. 
    Merge empty fields. (Golang)
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | package main | |
| import ( | |
| "fmt" | |
| "reflect" | |
| ) | |
| type Person struct { | |
| Name string | |
| Age int | |
| Positions []Position | |
| } | |
| type Position struct { | |
| Name string | |
| } | |
| func main() { | |
| data := data() | |
| data1 := data1() | |
| val := reflect.ValueOf(data).Elem() | |
| val1 := reflect.ValueOf(data1) | |
| for i := 0; i < val.Type().NumField(); i++ { | |
| if val.Field(i).IsZero() { | |
| f := val.FieldByName(val.Type().Field(i).Name) | |
| r := val1.FieldByName(val.Type().Field(i).Name) | |
| f.Set(r) | |
| } | |
| } | |
| fmt.Println(data) | |
| } | |
| func data() *Person { | |
| return &Person{} | |
| } | |
| func data1() Person { | |
| var pos []Position | |
| pos = append(pos, Position{ | |
| Name: "Mongo", | |
| }) | |
| pos = append(pos, Position{ | |
| Name: "Golang", | |
| }) | |
| return Person{ | |
| Name: "Umidjon", | |
| Age: 82, | |
| Positions: pos, | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment