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

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?

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.