猿问

指向结构戈朗问题的指针切片

我的存储库层中有一个函数,它应该返回一段指针,但代码无法正常工作。


var books []model.Book


func GetBooksByGenre(genre string) []*model.Book {

    var response []*model.Book

    for _, ele := range books {

        if ele.Genre == genre {

            response = append(response, &ele)

        }

    }

    return response

}

我正在尝试迭代书籍列表,并最终根据与输入类型匹配的书籍返回一段指针。genre


我调试并发现由于更新并弄乱var中的现有指针而存在问题eleresponse


问题是,如果以 as 的顺序插入了 3 本书,并且如果 GetBooksByGenre 用 as 或 调用,则输出将作为我迭代列表时的最后一个条目。genrecomedythrillerdramagenrecomedythrillerdrama


如何解决此问题?


叮当猫咪
浏览 75回答 1
1回答

拉风的咖菲猫

程序用变量 的地址填充切片。一种解决方法是使用切片元素的地址:elefunc GetBooksByGenre(genre string) []*model.Book {&nbsp; &nbsp; var response []*model.Book&nbsp; &nbsp; for i, ele := range books {&nbsp; &nbsp; &nbsp; &nbsp; if ele.Genre == genre {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; response = append(response, &books[i])&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return response}另一个修复方法是更改为 而不是 .将此代码与该更改一起使用:books[]*model.Book[]model.Bookfunc GetBooksByGenre(genre string) []*model.Book {&nbsp; &nbsp; var response []*model.Book&nbsp; &nbsp; for _, ele := range books {&nbsp; &nbsp; &nbsp; &nbsp; if ele.Genre == genre {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; response = append(response, ele)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return response}另一个解决方法是为每次迭代创建一个新变量,并使用该变量的地址:func GetBooksByGenre(genre string) []*model.Book {&nbsp; &nbsp; var response []*model.Book&nbsp; &nbsp; for _, ele := range books {&nbsp; &nbsp; &nbsp; &nbsp; if ele.Genre == genre {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ele := ele // <-- new variable&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; response = append(response, &ele)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return response}您可能希望在此处介绍前两个选项之一。
随时随地看视频慕课网APP

相关分类

Go
我要回答