当尝试在切片指针上移动时,我一直收到此错误。
app/domain/repositories/class_repository.go:24: cannot range over classes (type *[]entities.Class)
我究竟做错了什么?
这是结构:
package repositories import ( "mobifit/app/domain/entities" ) type ClassRepository struct { *Repository } func (c *ClassRepository) ClassesForLastNDays(days int) *[]entities.Class { classes := new([]entities.Class) query := Select("*"). From("Class"). Where("VisibleAt > CURRENT_TIMESTAMP() - INTERVAL ? DAY"). OrderBy("ClassTypeId"). Sql() c.Repository.Select(classes, query, days) c.populateClassRelationships(classes) return classes } func (c *ClassRepository) populateClassRelationships(classes *[]entities.Class) { for i := range classes { <<<<<<<<<<< Here is the problem class := classes[i] // ClassType c.Repository.GetById(class.ClassType, class.ClassTypeId) //Instructor c.Repository.GetById(class.Instructor, class.ClassType.InstructorId) // Equipment query := Select("E.*"). From("Equipment E"). Join("ClassEquipment CE on E.Id = CE.EquipmentId"). Where("CE.ClassId = ?"). Sql() c.Repository.Select(class.Equipment, query, class.Id) } }
这是Class结构:
package entities import ( "time" ) type Class struct { Id int ClassTypeId int VideoPath string VideoSize int Duration float64 CreatedAt time.Time VisibleAt time.Time NoLongerVisibleAt time.Time // Relationships ClassType ClassType Instructor User Equipment []Equipment }
您假设指向切片的指针将在迭代时自动取消引用。
事实并非如此,没有理由,因为切片已经是一种指针,从而使指向切片的指针完全无用。
从有效出发:
如果函数采用slice参数,则对slice元素所做的更改将对调用者可见,这类似于将指针传递给基础数组。
在内部,切片是由
这种结构非常小,使指针无用。