duanji1902 2018-11-19 23:33
浏览 9

分配等效类型的切片不起作用

Why doesn't this work?

package main

type Word uint8
type Memory []Word

func main() {
    bytes := []uint8{}
    memory := Memory{}
    bytes = memory
}

The compiler generates this error:

9:9: cannot use memory (type Memory) as type []byte in assignment

As I understand it, []uint8 and Memory should be mutually assignable.

  • 写回答

1条回答 默认 最新

  • duan246558 2018-11-19 23:40
    关注

    Here are the assignability rules

    In this particular case none of those is held, so the types are not assignable.

    Given you mentioned this answer is not detailed enough - let's run through every assignability rule: (for ease let's use A as a substitute for []uint8 and B as a substitute for []Word)

    • x's type is identical to T. --- Nope, A is not identical to B
    • x's type V and T have identical underlying types and at least one of V or T is not a defined type. --- Nope, both are defined types
    • T is an interface type and x implements T. --- None of them is an interface
    • x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a defined type. --- None of them is a channel
    • x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type. --- None of them holds nil value
    • x is an untyped constant representable by a value of type T. --- Nope, no constants involved

    So, as you can see - there is no way A is assignable to B.

    If you declare Memory as type Memory []uint8 it would work (as @RayfenWindspear mentioned in the comments), I'm sure though the question roots is more "why" not "how to fix".

    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么