dsjhejw3232 2017-08-11 16:23
浏览 349

Golang匿名结构初始化指针切片

From Chapter 7 of GOPL (Section 7.6), I noticed this line:

var tracks = []*Track{
     {"Go", "Delilah", "From the Roots Up", 2012, length("3m38s")},
     {"Go", "Moby", "Moby", 1992, length("3m37s")},
     {"Go Ahead", "Alicia Keys", "As I Am", 2007, length("4m36s")},
     {"Ready 2 Go", "Martin Solveig", "Smash", 2011, length("4m24s")},
}

I was kind of confused by how it initialized the slice of Track pointers. So later I tried the following example:

type Ex struct {
    A, B int
}

a := []Ex{Ex{1, 2}, Ex{3, 4}}
b := []Ex{{1, 2}, {3, 4}}
c := []*Ex{&Ex{1, 2}, &Ex{3, 4}}
d := []*Ex{{1, 2}, {3, 4}}
e := []*Ex{{1, 2}, &Ex{3, 4}}

I found all of the 5 cases are okay with no errors. The {1, 2} seems to be a structure called "anonymous struct", but it confuses me since it works fine even when I am trying to fill in *Ex pointers instead of Ex struct.

Furthermore, when I try the following code, it complains syntax error:

f := []*Ex{&{1, 2}, &{3, 4}} // Syntax Error!

Can somebody help explain what is actually going on in these cases?

  • 写回答

2条回答 默认 最新

  • doulan1866 2017-08-12 11:56
    关注

    Please give more detail on your structure definition of Ex.

    But, if Ex is implemented as this:

    type Ex struct {
        t interface{}
        o interface{}
    }
    

    you don't give a pointer of anonymous struct because, the definition it's not know.

    Also you can't do:

    variable := new({1, 2})
    // or
    variable := {1, 2}
    

    When you do:

    b := []Ex{{1, 2}, {3, 4}}
    // you create slice of Ex with two Ex struct
    // so b := []Ex{Ex{t:1,o:2}, Ex{t:3, o:4}}
    

    contrariwise:

    f := []*Ex{&{1, 2}, &{3, 4}}
    // you create slice of unknow definition type
    // f = []Ex{Ex{t: addressOfUnknowType, o: addressOfUnknowType}}
    

    I hope help you

    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程