访问嵌套结构中的切片元素的方法
时间:2024-03-03
浏览:196
作者:佚名
大家好,今天本人给大家带来文章《访问嵌套结构中的切片元素的方法》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!
问题内容
我有一个结构体 a,其中包含结构体 c 和其他数据类型的切片 b。我将它传递给 gohtml 模板。如何访问 gohtml 模板中 struct c 的元素。
type Str1 struct{
var_x string
var_y string
}
type Str2 struct {
var_a []Str1
var_b string
}
func main(){
B := make([]Str1], 0)
//code to append values of struct Str1 to Slice object B
str_var := Str2{B,"Good"}
tpl = template.Must(template.ParseGlob("template/*.gohtml"))
tpl.ExecuteTemplate(w, "example.gohtml", str_var)
}
我的问题是关于循环底层切片并访问 gohtml 代码中的“var_x & var_y”。在下面的示例中是“a,apple,b,ball...”
{[{a 苹果} {b 球} {c 猫} {a 空气} {b 蝙蝠} {c 外套} {d 狗} {e 耳朵}] 好}
解决方案
通过以大写 unicdoe 字符开头字段名称来导出字段。
type str1 struct {
var_x string
var_y string
}
type str2 struct {
var_a []str1
var_b string
}
使用 .运算符来引用点值的字段。
{{range .Var_a}}{{.Var_x}}: {{.Var_y}}; {{end}}
https://play.golang.org/p/KTlSWy10c4R
到这里,我们也就讲完了《访问嵌套结构中的切片元素的方法》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
热门专题
