Go 中的惯用类型转换 [英] Idiomatic Type Conversion in Go

查看:19
本文介绍了Go 中的惯用类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在玩 Go 并想知道在 Go 中执行惯用类型转换的最佳方法是什么.基本上我的问题在于 uint8uint64float64 之间的自动类型转换.根据我使用其他语言的经验,将 uint8uint64 相乘将产生 uint64 值,但在 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.

谢谢!

推荐答案

对于非常量值没有隐式类型转换.

There are no implicit type conversions for non-constant values.

你可以写

var x float64
x = 1

但是你不会写

var x float64
var y int

y = 1
x = y

请参阅规范以供参考.

有一个很好的理由,不允许自动/隐式类型转换,因为它们可以变得非常凌乱,必须学习许多规则才能规避各种警告这可能会发生.采用 C 中的整数转换规则 例如.

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.

这篇关于Go 中的惯用类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆