避免过多的转换

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

Avoid too much conversion

问题

我当前的Go代码中有一些部分看起来像这样:

i := int(math.Floor(float64(len(l)/4)))

由于math.Floor中的某些函数类型签名,这种冗长似乎是必要的,但它可以简化吗?

英文:

I have some parts in my current Go code that look like this:

i := int(math.Floor(float64(len(l)/4)))

The verbosity seems necessary because of some function type signatures like the one in math.Floor, but can it be simplified?

答案1

得分: 12

一般来说,Go语言的严格类型导致了一些冗长的表达式。冗长并不意味着口吃。类型转换可以做一些有用的事情,有必要明确地表达这些有用的事情。

简化的关键是不写不必要的类型转换,为此你需要参考诸如语言定义之类的文档。

在你的具体情况中,你需要知道len()返回int类型,并且值大于等于0。你需要知道4是一个常量,在这个表达式中将会被赋予int类型,并且你需要知道整数除法将返回整数商,而在这种情况下将是一个非负的int,实际上正是你想要的答案。

i := len(l)/4

这个例子很简单。

英文:

In general, the strict typing of Go leads to some verbose expressions. Verbose doesn't mean stuttering though. Type conversions do useful things and it's valuable to have those useful things explicitly stated.

The trick to simplification is to not write unneeded type conversions, and for that you need to refer to documentation such as the language definition.

In your specific case, you need to know that len() returns int, and further, a value >= 0. You need to know that 4 is a constant that will take on the type int in this expression, and you need to know that integer division will return the integer quotient, which in this case will be a non-negative int and in fact exactly the answer you want.

i := len(l)/4

This case is an easy one.

答案2

得分: 2

我不确定Go如何处理整数除法和整数转换,但通常是通过截断来实现的。因此,假设len(l)是一个int类型的变量:

i:=len(l)/4

否则,i:= int(len(l))/4i:=int(len(l)/4) 应该可以工作,其中第一个理论上比第二个稍微快一些。

英文:

I'm not 100% sure how Go deals with integer division and integer conversion, but it's usually via truncation. Thus, assuming len(l) is an int

i:=len(l)/4

Otherwise i:= int(len(l))/4 or i:=int(len(l)/4) should work, with the first being theoretically slightly faster than the second.

huangapple
  • 本文由 发表于 2012年12月20日 06:52:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/13962610.html
匿名

发表评论

匿名网友

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

确定