本文介绍了关于将uint8转换为int8的困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将uint8转换为int,所以我写了一个const 0xfc,并尝试使用int8(0xfc)对其进行转换.但是,代码会引发错误:

I want to convert uint8 to int, so I write a const 0xfc, and try to use int8(0xfc) to convert it. However the code raises an error:

package main

import (
    "fmt"
)

func main() {
    a := int8(0xfc)  // compile error: constant 252 overflows int8
    b := a
    fmt.Println(b)
}

但是如果我在分配后推迟类型转换,则代码可以解决.

But if I defer the type conversion after assignment, the code can work around.

package main

import (
    "fmt"
)

func main() {
    a := 0xfc
    b := int8(a)  // ok
    fmt.Println(b)
}

我的问题:

  • 这两个代码之间有什么区别吗?
  • 为什么第一个会引发编译错误?

推荐答案

  1. 请参阅: https://golang.org/ref/spec#Constant_expressions
uint(-1)     // -1 cannot be represented as a uint
int(3.14)    // 3.14 cannot be represented as an int
int64(Huge)  // 1267650600228229401496703205376 cannot be represented as an int64
Four * 300   // operand 300 cannot be represented as an int8 (type of Four)
Four * 100   // product 400 cannot be represented as an int8 (type of Four)
  1. 请参阅: https://blog.golang.org/constants
  1. see:https://blog.golang.org/constants
    type Char byte
    var c Char = '世' // Error: '世' has value 0x4e16, too large.

如果编译器抱怨您使用了常量,则可能是真正的错误.

If the compiler complains about your use of a constant, it's likely a real bug like this.


是的,这是要走的路:


    var b byte = 0xff
    i32 := int32(int8(b))
    fmt.Println(i32) // -1

这篇关于关于将uint8转换为int8的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 18:07
查看更多