Home > database >  (Golang) handle and format nils from list
(Golang) handle and format nils from list

Time:08-29

Say i am expecting this list from a query to a backend:

Name: Volvo, EngineType: 2NR-FE, Warranty: 2 years, Distance covered: 9000km.

In the case e.g EngineType is empty which equals to a nil, I want to set that to "None" or if Warranty == nil i want to set that to "No warranty found"

Here is my loop:

    for _, res := range resp.Automobiles {
        if res.Cars != nil {
            for _, car := range res.Cars {
                if car == nil || car.EngineType == nil {
                    fmt.Println("None")
                } else if car.Warranty == nil {
                    fmt.Println("NO Warranty Found")
                } else {
                    details = []string{*car.Name, *car.EngineType, *car.Warranty, *car.DistanceCovered}
                    fmt.Println(strings.Join(details, ","))
                }
            }
        }
    }
}

Output I'm expecting if Warranty == nil and EngineType == nil respectively:

Volvo, 2NR-FE, No warranty found, 9000km
Volvo, None, 2 years, 9000km

Output I'm getting:

No warranty Found
None

My code just sets the line to the first expression it checks

I know my code might be shitty, I'm still getting used to Go.

CodePudding user response:

Output I'm getting

Because you only print the other details of the car if both EngineType and Warranty is not nil. If either is nil, the other details are omitted.

You can dry out your code with a helper function like this:

func StrOrDefault(s *string, default string) string {
   if s == nil {
     return default
   } else {
      return *s
   }
}

You'll also have to decide what output you want, if any, if car == nil. In the code below, I output "None" if car == nil.

    for _, res := range resp.Automobiles {
        if res.Cars == nil {
            continue
        }
        for _, car := range res.Cars {
            if car == nil {
                fmt.Println("None")
                continue
            }
            details = []string{
                *car.Name,
                StrOrDefault(car.EngineType, "None"),
                StrOrDefault(car.Warranty, "No warranty found"),
                *car.DistanceCovered,
            }
            fmt.Println(strings.Join(details, ","))
        }
    }

CodePudding user response:

You might prefer using the standard library templating mechanism over fmt routines. As https://stackoverflow.com/a/32775203/7050833 shows, you can then say 'if not'...'else' to capture nil vs. non-nil cases.

  • Related