dongye6377 2015-03-29 18:11
浏览 49
已采纳

Golang基础类型

In this code snippet from the spec

type T1 string
type T2 T1
type T3 []T1
type T4 T3

The spec says:

The underlying type of string, T1, and T2 is string.
The underlying type of []T1, T3, and T4 is []T1.

Why is the underlying type of T2 not T1, but string?
Shouldn't the underlying type of T4 instead be []string and not []T1 if the underlying type of T1 is string?
Confused.

  • 写回答

1条回答 默认 最新

  • dqyz48470 2015-03-29 19:01
    关注

    The spec mentions:

    Each type T has an underlying type: If T is one of the predeclared boolean, numeric, or string types, or a type literal, the corresponding underlying type is T itself.
    Otherwise, T's underlying type is the underlying type of the type to which T refers in its type declaration.

    T2 refers in its type declaration to T1, which has the underlying type string.

    It is important for the underlying type of T2 to be string, because it will help for Assignability where

    A value x is assignable to a variable of type T ("x is assignable 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.

    This is also detailed in "Golang: Why can I type alias functions and use them without casting?"


    When it comes to the underlying type of T4, we are talking about an underlying unnamed type []T1.

    And again, the assignability rule says you can assign []T1 to T4 (since []T1 is not a named type): its underlying type stops at the first not-named type ([]T1).

    See this example on playground

    var t3 T3 = []T1{"a", "b"}
    fmt.Println("t3='%+v'", t3)
    // var t4 T4 = []string{}
    // cannot use []string literal (type []string) as type T4 in assignment
    var t4 T4 = T4(t3)
    fmt.Println("t4='%+v'", t4)
    t4 = []T1{T1("c"), T1("d")}
    fmt.Println("t4='%+v'", t4)
    

    Output:

    t3='%+v' [a b]
    t4='%+v' [a b]
    t4='%+v' [c d]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭