(Golang)处理和格式化列表中的nil值

huangapple go评论80阅读模式
英文:

(Golang) handle and format nils from list

问题

以下是我翻译好的内容:

假设我从后端查询中期望得到以下列表:

名称:Volvo,
发动机类型:2NR-FE,
保修期:2年,
行驶里程:9000公里。

在某些情况下,例如发动机类型为空(等于nil),我希望将其设置为"None",或者如果保修期等于nil,我希望将其设置为"No warranty found"。

这是我的循环代码:

	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, ","))
				}
			}
		}
	}
}

我期望的输出结果是,如果Warranty等于nil,EngineType等于nil:

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

我实际得到的输出结果是:

No warranty Found
None

我的代码只会将行设置为它检查的第一个表达式。

我知道我的代码可能不太好,我还在逐渐熟悉Go语言。

英文:

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.

答案1

得分: 2

> 我得到的输出

因为只有在EngineType和Warranty都不为nil时,才会打印出车辆的其他细节。如果其中一个为nil,其他细节将被省略。

你可以使用以下辅助函数来简化你的代码:

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

你还需要决定在car == nil时,你想要什么输出(如果有的话)。在下面的代码中,如果car == nil,我输出了"None"。

	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, ","))
		}
	}
英文:

> 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, ","))
		}
	}

答案2

得分: 0

你可能更喜欢使用标准库的模板机制而不是 fmt 函数。正如 https://stackoverflow.com/a/32775203/7050833 所示,你可以使用 "if not" ... "else" 来处理 nil 和非 nil 的情况。

英文:

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.

huangapple
  • 本文由 发表于 2022年8月29日 02:53:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/73521368.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定