duannaikuang1301 2019-03-01 01:50
浏览 17

理解go中的类型转换时的困惑

    package main

    import (
    "fmt"
    )

    type val []byte

   func main() {
    var a []byte = []byte{0x01,0x02}
    var b val = a
    fmt.Println(a)
    fmt.Println(b)
}

o/p: [1 2] [1 2]

Here, my understanding is that a,b identifier share the same underlying type([]byte). so we can exchange the values b/w 2 variables.

package main

import (
    "fmt"
)

type abc string

func main() {
    fm := fmt.Println
    var second = "whowww"
    var third abc = second //compile Error at this line 12
    fm(second)
    fm(third)

}

In line 12 I'm not able to assign the variable. This Error can be eliminated by using Explicit conversion T(x), I want to understand why we cannot do implicit conversion As both variables share the same underlying-type, but I'm not able to assign it.

can someone explain the reason behind these?

IF possible provide me the good documentation for type conversions between variables, struct types, function parameters.

  • 写回答

1条回答 默认 最新

  • dongluanan7163 2019-03-05 16:25
    关注

    This is by design. The Go programming language requires assignment between different types to have an explicit conversion.

    It might look like you're simply aliasing the string type to have a different name, but you're technically creating a new type, with a storage type of string, there's a subtle difference.

    The way you would define an alias in Go (as of 1.9) is subtly different, theres an equals sign.

    type abc = string

    If there's any confusion as to why Go doesn't have implicit conversions, it might seem silly when you're only dealing with an underlying string type, but with more complex types, it ensures that the programmer knows just by looking at the code that a conversion is happening.

    Its especially helpful in debugging an application, particularly when converting between numeric types to know when a conversion is taking place, so that if there is a truncation of bits i.e. uint64 to uint32, it is obvious to see where that is happening.

    https://tour.golang.org/basics/13

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?