You've run into the distinction between named types and unnamed types:
https://golang.org/ref/spec#Properties_of_types_and_values

int, TI, and TIS are named types. []int is an unnamed type. The rules for
assignability say:

> A value x is assignable to a variable of type T ("x is assignable to T")
in any of these cases:
>
> • 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 named type.
> • …

In each case, assigning TI to int and TIS to []int, the types are not
identical, so the first rule doesn't apply. However, since []int is an
unnamed type, and has the same underlying type as TIS, the second rule says
you can assign a value of type TIS to type []int. Since TI and int are both
named types the second rule doesn't apply between them. None of the
remaining assignability rules apply either, so the assignment from TI to
int is illegal.

The reason assignment isn't allowed between two named types that aren't
identical is because named types are supposed to represent entirely
distinct types. If I have types Meters and Kilograms, it would clearly be
wrong for the compiler to let me assign between them, even if they have the
same underlying representation. If the compiler didn't prevent this, then
named types would be significantly less useful for ensuring program
correctness and would instead serve as glorified documentation.

The reason this restriction is lifted when one of the types is unnamed is
for ease of use. Often, literal values (like function literals) have an
unnamed type, and it would be cumbersome to have to convert them every time
you want to initialize a corresponding named type. Also, it's quite common
to want to perform general purpose slice operations on values that have a
named slice type. Operations on unnamed slice types don't make any
assumptions about the meaning of the slice, so there's less risk of a
semantic mismatch between what is expected and what is provided than there
is between two named types (like Meters and Kilograms).

On Sat, Jul 16, 2016 at 4:15 PM T L <tapir....@gmail.com> wrote:

>
> package main
>>
>> func fi(i int) {}
>> func fis(is []int) {}
>>
>> type TI int
>> type TIS []int
>>
>> func main() {
>>     var ti TI
>>     fi(ti) // cannot use ti (type TI) as type int in argument to fi
>>
>>     var tis TIS
>>     fis(tis) // no problems!
>> }
>>
>> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to