我正在尝试迭代切片值并更新一个或多个值,通过索引访问它们或迭代它们。然后我有以下问题。
package main
import "fmt"
type Member struct {
Name, Surname string
Age int
}
type Members []Member
func main() {
members1 := Members{
{"Bob", "Doe", 30},
{"Jack", "Doe", 30},
{"John", "Doe", 30},
}
members1.ModifyName()
members1.ModifyAllNames1()
members1.ModifyAllNames2()
fmt.Println(members1)
}
func (members *Members) ModifyName() {
*members[0].Name = "-"
}
func (members *Members) ModifyAllNames1() {
for i := 0; i < len(*members); i++ {
*members[i].Name = "-"
}
}
func (members *Members) ModifyAllNames2() {
for _, m := range *members {
m.Name = "-"
}
}
然后我收到以下错误:
invalid operation: members[0] (type *Members does not support indexing)
invalid operation: members[i] (type *Members does not support indexing)
答案 0 :(得分:60)
类型*Members
不支持索引,Members
类型。
m := make([]Members, 5)
pm := &m
m[:2] // good
pm[:2] // bad
(*pm)[:2] // good
http://play.golang.org/p/_26TUBHdDm
package main
import "fmt"
type Member struct {
Name, Surname string
Age int
}
type Members []Member
func main() {
members1 := Members{
{"Bob", "Doe", 30},
{"Jack", "Doe", 30},
{"John", "Doe", 30},
}
members1.ModifyName()
members1.ModifyAllNames1()
members1.ModifyAllNames2()
fmt.Println(members1)
}
func (members *Members) ModifyName() {
(*members)[0].Name = "-"
}
func (members *Members) ModifyAllNames1() {
for i := 0; i < len(*members); i++ {
(*members)[i].Name = "-"
}
}
func (members *Members) ModifyAllNames2() {
for _, m := range *members {
m.Name = "-"
}
}
答案 1 :(得分:1)
func (members *Members) ModifyName() { *members[0].Name = "-" }
invalid operation: members[0] (type *Members does not support indexing)
问题是运算符的关联性和/或优先级,尽管我找不到Golang规范中明确涵盖的特定情况。
表达式*members[0].Name
似乎与*(members[0].Name)
等效,因此,要获得正确的指针引用,您必须在必须取消引用的项目周围显式使用一对括号,{ {1}}。