美文网首页
golang类型间强制转换

golang类型间强制转换

作者: 小易哥学呀学 | 来源:发表于2021-11-15 10:07 被阅读0次

    强转规则

    假设我们要把right强制转换后赋值给left

    left = leftType(right)
    

    left与right需满足以下规则之一:

    (1)双方有相同的底层类型。

    (2)双方都是整数类型

    (3)双方都是浮点类型

    (4)双方都是复数类型

    (5)right是整数类型或[]byte或[]rune,left是string类型。

    (6)right是string类型,left是[]byte或[]rune。

    底层类型相同,例子:

    package main
    
    import (
      "github.com/davecgh/go-spew/spew"
    )
    
    type Int struct {
      a int
    }
    
    type PointLeft *Int
    type PointRight PointLeft
    
    func main() {
      // left底层类型是*Int
      var left PointLeft
      // right底层类型是*Int
      var right PointRight
    
      left, right =  &Int{1},  &Int{1}
    
      // 可以强转
      // left与right底层类型相同
      left = PointLeft(right)
    
      spew.Dump(left, right)
    }
    

    整数、浮点数、复数,例子:

    package main
    
    import (
      "github.com/davecgh/go-spew/spew"
    )
    
    func main() {
      /*
      int
       */
      var Int int = 1
      var Int8 int8 = 8
      var Int32 int32 = 32
      var Int64 int64 = 64
    
      Int = int(Int8)
      spew.Dump(Int)
    
      Int = int(Int32)
      spew.Dump(Int)
    
      Int = int(Int64)
      spew.Dump(Int)
    
      /*
      float
       */
      var Float32 float32 = 1.1
      var Float64 float64 = 1.1
    
      Float32 = float32(Float64)
      spew.Dump(Float32, Float64)
    
      /*
      complex
       */
      var Complex64 complex64 = complex(1,2)
      var Complex128 complex128 = complex(1,2)
    
      Complex64 = complex64(Complex128)
      spew.Dump(Complex64, Complex128)
    
    }
    

    string强转为[]byte,[]rune,例子:

    package main
    
    import (
      "github.com/davecgh/go-spew/spew"
    )
    
    func main() {
      var aString string
      var b []byte
      var c []rune
    
      aString = "a"
    
      // 字符串不能转为整数类型
      // var a int
      // a = int(aString)
    
      // string to []byte
      b = []byte(aString)
      spew.Dump(b)
    
      // string to []rune
      c = []rune(aString)
      spew.Dump(c)
    }
    

    整数类型、[]byte、[]rune强转为string,例子:

    package main
    
    import (
      "github.com/davecgh/go-spew/spew"
    )
    
    func main() {
      var a int
      var b []byte
      var c []rune
    
      a = 97
      b = []byte{97, 98}
      c = []rune{97, 98}
    
      var aString string
    
      // 这里a用的int,其他int类型也可以
      aString = string(a)
      spew.Dump(aString)
    
      // byte to string
      aString = string(b)
      spew.Dump(aString)
    
      // rune to string
      aString = string(c)
      spew.Dump(aString)
    }
    

    相关文章

      网友评论

          本文标题:golang类型间强制转换

          本文链接:https://www.haomeiwen.com/subject/wzxhtrtx.html