du2986 2018-07-07 09:02
浏览 38
已采纳

自定义切片类型和基础类型之间的分配

Go assignment shows error for int but not for []int slice.

working code here

package main

import (
    "fmt"
)

type testType []int

func main() {
    var i testType
    var t []int
    t = i

    fmt.Println("Hello, playground", t, i)
}

However, if it is int type the compiler will surely show errors here:

cannot use i (type testType) as type int in assignment
package main

import (
    "fmt"
)

type testType int

func main() {
    var i testType
    var t int
    t = i

    fmt.Println("Hello, playground", t, i)
}

Why does it error out for the custom int type and not the custom []int type?

  • 写回答

1条回答 默认 最新

  • drxdn40242 2018-07-07 09:19
    关注

    It is defined in Go language specification for assignment types:

    A value x is assignable to a variable of type T ("x is assignable to T") if one of the following conditions applies:

    • x's type is identical to T.
    • x's type V and T have identical underlying types and at least one of V or T is not a defined type.
    • T is an interface type and x implements T.
    • 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.
    • x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.
    • x is an untyped constant representable by a value of type T.

    In your case []int is a slice and not named type. That's why the compiler did not complain. For more information on named types go through Go specification for types:

    A type determines the set of values and operations specific to values of that type. Types may be named or unnamed. Named types are specified by a (possibly qualified) type name; unnamed types are specified using a type literal, which composes a new type from existing types.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?