GoLang的结构

GoLang的结构,第1张

概述我刚刚开始使用GoLang,我正在查看他们的一个教程( https://golang.org/doc/code.html). 在他们的一个例子中,他们将一个变量设置为一个结构,但是我很困惑他们如何在下面的for循环中访问结构的元素?有人可以澄清吗?非常感谢! 码: package stringutilimport "testing"func TestReverse(t *testing.T 我刚刚开始使用Golang,我正在查看他们的一个教程( https://golang.org/doc/code.html).

在他们的一个例子中,他们将一个变量设置为一个结构,但是我很困惑他们如何在下面的for循环中访问结构的元素?有人可以澄清吗?非常感谢!

码:

package stringutilimport "testing"func TestReverse(t *testing.T) {    cases := []struct {        in,want string    }{        {"Hello,world","dlrow,olleH"},{"Hello,世界","界世,{"",""},}    for _,c := range cases {        got := Reverse(c.in)        if got != c.want {            t.Errorf("Reverse(%q) == %q,want %q",c.in,got,c.want)        }    }}
下面是代码,其中包含一些注释,以帮助阐明每个语句在此中的作用.
import "testing"func TestReverse(t *testing.T) {    cases := []struct { // declaration of anonymous type        in,want string // fIElds on that type called in and want,both strings    }{        {"Hello,} // composite literal initilization    // note the use of := in assigning to cases,that op combines declaration and assignment into one statement    for _,c := range cases { // range over cases,ignoring the index - the underscore means to discard that return value        got := Reverse(c.in) // c is the current instance,access in with the familiar dot notation        if got != c.want { // again,access operator on c,the current instance            t.Errorf("Reverse(%q) == %q,c.want) // more access        }    }}

如果有帮助,请告诉我.如果某些陈述仍然没有意义,我可以尝试用口语提供更多的摘要或添加更多细节.另外,如果你不熟悉集合中的范围’范围’,则返回k,v,其中k是索引或键,v是值.

编辑:有关声明/启动案件的详细信息

cases := []struct {        in,want string    }

第一对花括号内的这一位是结构的定义.这是一个匿名类型,正常的声明看起来像这样;

type case strcut {        in string        want string    }

如果你有这样的东西,那么在这个包的范围内会有一个叫做case的类型(如果你想把它设为’public’,那么就不需要导出它,所以它需要是Case类型).相反,examples struct是匿名的.它与普通类型的工作方式相同,但作为开发人员,您将无法引用该类型,因此您只能使用此处初始化的集合.在内部,此类型与具有2个未导出字段的字符串的任何其他结构相同.这些字段以in和named命名.请注意,在这里的赋值中:= [] struct你在struct之前有[]这意味着你要声明这个匿名类型的切片.

下一点,称为静态启动.这是用于初始化集合类型的语法.这些嵌套位中的每一个如{“”,“”}都是这些匿名结构之一的声明和启动,再次用花括号表示.在这种情况下,您分别为in和want分配两个空字符串(如果不使用名称,则顺序与定义中的顺序相同).外面的一对括号用于切片.如果你的切片是整数或字符串,那么你只需要在那里没有额外的嵌套级别,如myInts:= [] int {5,6,7}.

{        {"Hello,}
总结

以上是内存溢出为你收集整理的GoLang的结构全部内容,希望文章能够帮你解决GoLang的结构所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1293714.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存