我刚开始使用GoLang,我正在查看他们的一个教程(https://golang.org/doc/code.html).
在他们的一个例子中,他们将一个变量设置为一个结构,但是我很困惑他们如何在下面的for循环中访问结构的元素?有人可以澄清吗?非常感谢!
码:
package stringutil
import "testing"
func TestReverse(t *testing.T) {
cases := []struct {
in, want string
}{
{"Hello, world", "dlrow ,olleH"},
{"Hello, ??", "?? ,olleH"},
{"", ""},
}
for _, c := range cases {
got := Reverse(c.in)
if got != c.want {
t.Errorf("Reverse(%q) == %q, want %q", c.in, got, c.want)
}
}
}
Run Code Online (Sandbox Code Playgroud)
下面是代码,其中包含一些注释,以帮助阐明每个语句在此中的作用.
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, world", "dlrow ,olleH"},
{"Hello, ??", "?? ,olleH"},
{"", ""},
} // 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, want %q", c.in, got, c.want) // more access
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果有帮助,请告诉我.如果某些陈述仍然没有意义,我可以尝试用口语提供更多的摘要或添加更多细节.此外,仅供参考,如果你不熟悉的范围内"范围"一个集合,返回k, v这里k是索引或键和v值.
编辑:关于声明/启动的详细信息 cases
cases := []struct {
in, want string
}
Run Code Online (Sandbox Code Playgroud)
第一对花括号内的这一位是结构的定义.这是一个匿名类型,正常的声明看起来像这样;
type case strcut {
in string
want string
}
Run Code Online (Sandbox Code Playgroud)
如果你有这样的东西,那么会有一个case在这个包的范围内调用的类型(如果你想让它'公开',那么就不需要导出它,所以它需要type Case改为).相反,examples struct是匿名的.它与普通类型的工作方式相同,但作为开发人员,您将无法引用该类型,因此您只能使用此处初始化的集合.在内部,此类型与具有2个未导出字段的字符串的任何其他结构相同.这些字段的名称in和want.请注意,在此处的赋值中,cases := []struct您[]在struct此之前意味着您要声明此匿名类型的一部分.
下一点,称为静态启动.这是用于初始化集合类型的语法.这些嵌套位中的每{"", ""}一个都是这些匿名结构之一的声明和启动,再次用花括号表示.在这种情况下,你要指定两个空字符串in,并want分别(如果你不使用的名称,顺序是一样的定义).外面的一对括号用于切片.如果你的切片是整数或字符串,那么你只需要将值放在那里,而不需要额外的嵌套级别myInts := []int{5,6,7}.
{
{"Hello, world", "dlrow ,olleH"},
{"Hello, ??", "?? ,olleH"},
{"", ""},
}
Run Code Online (Sandbox Code Playgroud)