duanbo2048 2017-05-01 21:22
浏览 13

函数返回指向结构片的指针仅返回1

I have a function that basically looks like this:

func (db *datastoreDB) GetAllUsers(ctx context.Context) (*[]User, error) {
  query := datastore.NewQuery("User")
  var users []User
  _, err := db.client.GetAll(ctx, query, &users)
  return &users, nil
}

with the struct:

type User struct {
  username string
  password []byte
}

Now, if I try to call

users, err := models.DB.GetAllUsers(ctx)
log.Println(users)

then it will only print 1 user, even though there are many..

I tried to Print using users[0], users[1] but that returned errors, also tried with *users[1], &users[1], and for i, _ range users { log.Println(users[i]) }

Haven't quite been able to understand when/how to use * and & even though I read many online tutorials, so often just do trail and error.. I doubt there is anything wrong with my datastore GetAll function, so I assume I just fail to properly access/return the struct slice but feel like I tried everything..

  • 写回答

1条回答 默认 最新

  • doudi1979 2017-05-01 22:42
    关注

    Slices include pointers; in fact they are structs with a pointer to an array and some information as to where the slice begins and ends.

    A slice is a descriptor of an array segment. It consists of a pointer to the array, the length of the segment, and its capacity (the maximum length of the segment)

    The asterix before a type designates that type as a pointer (unless it already is a pointer, in that case it dereferences it). I think you probably meant to write []*User, which will expect a slice of pointers to Users. You can think of [] and User as distinct types.

    To create a slice, the simplest way is probably with make();

    You can try, instead of var users []User,

    users := make([]*User, 0) // replace 0 with the amount of nil values in the slice you're looking to fill
    

    Finally, you'll have to remove the & signs you place before users, as these pass the pointer to a value (but as I pointed out above, slices are already pointers)


    To better understand pointers, Dave Cheney recently wrote a blog post titled Understand Go pointers in less than 800 words or your money back, you might find it useful.

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法