问题描述
我正在和Go一起玩,并且想知道在Go中执行惯用类型转换的最佳方式。基本上,我的问题是在 uint8
, uint64
和 float64
。根据我对其他语言的经验,将 uint8
与 uint64
相乘将产生 uint64
的价值,但不是这样在去。
这是我建立的一个例子,我问这是编写这种代码的惯用方式或者我错过了一个重要的语言结构。 从我的角度来看,由于所有显式类型转换,上限值的计算看起来并不复杂。 感谢! -constant values。 您可以编写 但是你不能写 请参阅 有一个很好的理由,不允许自动/隐式类型转换,因为 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 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. From my point of view the calculation of the ceiling value seems unnecessary complex because of all the explicit type conversions. Thanks! There are no implicit type conversions for non-constant values. You can write But you cannot write See the spec for reference. There's a good reason, to not allow automatic/implicit type conversions, as they canbecome very messy and one has to learn many rules to circumvent the various caveatsthat may occur. Take the Integer Conversion Rules in C for example. 这篇关于Go中的习惯式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
pre $ $ $ $ $ $ $ $ $
$ b import(math ;fmt)
const(Width = 64)
func main(){
var index uint32
var bits uint8
index = 100
bits = 3
var c uint64
//这是感兴趣的线vvvv
c = uint64(数学.Ceil(float64(index * uint32(bits))/ float64(Width)))
fmt.Println(Test:%v \ n,c)
}
var x float64
x = 1
var x float64
var y int
y = 1
x = y
变得非常混乱,必须学习很多规则来规避可能发生的各种警告
。在C中使用举例说明。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.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\n", c)
}
var x float64
x = 1
var x float64
var y int
y = 1
x = y