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.

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

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决