Go中的惯用类型转换
I was playing around with Go and was wondering what the best way is to perform idiomatic type conversions in Go. Basically my problem lays within automatic type conversions between uint8
, uint64
, and float64
. From my experience with other languages a multiplication of a uint8
with a uint64
will yield a uint64
value, but not so in go.
Here is an example that I build and I ask if this is the idiomatic way of writing this code or if I'm missing an important language construct.
package main
import ("math";"fmt")
const(Width=64)
func main() {
var index uint32
var bits uint8
index = 100
bits = 3
var c uint64
// This is the line of interest vvvv
c = uint64(math.Ceil(float64(index * uint32(bits))/float64(Width)))
fmt.Println("Test: %v
", c)
}
From my point of view the calculation of the ceiling value seems unnecessary complex because of all the explicit type conversions.
Thanks!
我正在玩Go,想知道在Go中执行惯用类型转换的最佳方法是什么。 基本上,我的问题在于 这是我构建的一个示例,请问这是编写代码的惯用方式还是我缺少重要的语言构造? p>
从我的角度来看,计算上限值 由于所有显式类型转换,似乎不必要的复杂性。 p>
谢谢! p>
div> uint8 code>,
uint64 code>和
float64 code>之间的自动类型转换。 根据我在其他语言上的经验,将
uint8 code>与
uint64 code>相乘会产生一个
uint64 code>值,但实际上并非如此。 p >
package main
import(“ math”;“ fmt”)
const(Width = 64)
func main(){
var index uint32
var bits uint8
\ n索引= 100
位= 3
var c uint64
//这是感兴趣的行vvvv
c = uint64(math.Ceil(float64(index * uint32(bits))/ float64(Width) ))
fmt.Println(“ Test:%v
”,c)
}
code> pre>
There are no implicit type conversions for non-constant values.
You can write
var x float64
x = 1
But you cannot write
var x float64
var y int
y = 1
x = y
See the spec for reference.
There's a good reason, to not allow automatic/implicit type conversions, as they can become very messy and one has to learn many rules to circumvent the various caveats that may occur. Take the Integer Conversion Rules in C for example.
For example,
package main
import "fmt"
func CeilUint(a, b uint64) uint64 {
return (a + (b - 1)) / b
}
func main() {
const Width = 64
var index uint32 = 100
var bits uint8 = 3
var c uint64 = CeilUint(uint64(index)*uint64(bits), Width)
fmt.Println("Test:", c)
}
Output:
Test: 5