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

问题描述

我正在和Go一起玩,并且想知道在Go中执行惯用类型转换的最佳方式。基本上,我的问题是在 uint8 uint64 float64 。根据我对其他语言的经验,将 uint8 uint64 相乘将产生 uint64 的价值,但不是这样在去。



这是我建立的一个例子,我问这是编写这种代码的惯用方式或者我错过了一个重要的语言结构。

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

从我的角度来看,由于所有显式类型转换,上限值的计算看起来并不复杂。



感谢!

解决方案

-constant values。



您可以编写

  var x float64 
x = 1

但是你不能写

  var x float64 
var y int

y = 1
x = y

请参阅

有一个很好的理由,不允许自动/隐式类型转换,因为
变得非常混乱,必须学习很多规则来规避可能发生的各种警告
。在C中使用举例说明。


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

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

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 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中的习惯式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:43