douliao7930
douliao7930
2014-12-23 19:27

字段:值和值初始值设定项的混合

Why can I not create the following, with an anonymous field?

type T1 struct {
    T1_Text string
}

type T2 struct {
    T2_Text string
    T1
}

used in func ..

t := T2{
    T2_Text: "Test",
    T1{T1_Text: "Test"},
}

Gives me: mixture of field:value and value initializers?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • duanpanhuo0618 duanpanhuo0618 4年前

    A brief explanation.

    The reason you get that is because you are allowed to only use one of the two types of initializers and not both.

    i.e. you can either use field:value or value.

    Using your example you either do

    field:value

    t := T2{
        T2_Text: "Test",
        T1: T1{T1_Text: "Test"},
    }
    

    or only values

    t := T2{
        "Test",
        T1{"Test"},
    }
    

    Hope that explains the why

    点赞 评论 复制链接分享
  • duanba2001 duanba2001 5年前

    Missing the attribute name T1 for assignment.

    t := T2{
        T2_Text: "Test",
        T1:      T1{T1_Text: "Test"},
    }
    

    P.S. Just moved @twotwotwo's comment to an answer.

    点赞 评论 复制链接分享

为你推荐